WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Excluding pages from search breaks Media Library search (2 posts)

  1. chadrew
    Member
    Posted 2 years ago #

    I've found the following function for excluding pages from search (or to be more precise, showing only posts in search):

    function SearchFilter($query) {
        if ($query->is_search) {
            $query->set('post_type','post');
        }
        return $query;
    }
    
    add_filter('pre_get_posts','SearchFilter');

    It works great, but it also prevents the Media Library search from returning any results. So I thought, maybe I could include attachments as well, like this:

    function SearchFilter($query) {
        if ($query->is_search) {
            $query->set('post_type',array(post,attachment));
        }
        return $query;
    }
    
    add_filter('pre_get_posts','SearchFilter');

    Media Library search now works, but it also returns the following error every time:

    Warning: Illegal offset type in isset or empty in /home/user/public_html/wp-includes/post.php on line 825

    Any way to fix this?

    Here's the line from post.php:

    function get_post_type_object( $post_type ) {
    global $wp_post_types;

    if ( empty($wp_post_types[$post_type]) )
    return null;

    return $wp_post_types[$post_type];
    }

    (I know very little about PHP. I assume I can't use an array for post_type for some reason?)

  2. chadrew
    Member
    Posted 2 years ago #

    OK I've searched around and it looks like query can't contain multiple post types, and it's a known issue:

    http://core.trac.wordpress.org/ticket/16949

    However, I was able to fix it by using this:

    function SearchFilter($query) {
        if ($query->is_search && !$query->is_admin) {
            $query->set('post_type','post');
        }
        return $query;
    }
    
    add_filter('pre_get_posts','SearchFilter');

    This way this function doesn't affect the admin panel, so I can use the Media Library search without problems... Yay!

Topic Closed

This topic has been closed to new replies.

About this Topic