2

I am aware of the option to set exclude_from_search => 'true' when registering a custom post type. But what are the other options?

2 Answers 2

2

You can use the pre_get_posts hook. Do note though, this hook filters the query on both the front-end and admin. For example, we could do something like this:

function search_post_types( $query ) {
    if( is_admin() ) {
        return $query;
    }

    if ( $query->is_search && $query->is_main_query() ) {
        $query->set( 'post_type', array( 'post', 'page' ) );
    }
}
add_action( 'pre_get_posts', 'search_post_types' );

I'm not sure there's a way to exclude it using pre_get_posts but more along the lines of include specific post types only, in the example above I'm only including Posts and Pages, nothing else.


Another method is to get all post types and create an array of post types we actually want to exclude. First we use the function get_post_types() which does have some arguments to exclude built-in post types but for this example we will get everything. Once we've gotten our post types we can create an exclude array and array_diff(), here's what it looks like:

function search_post_types( $query ) {
    if( is_admin() ) {
        return $query;
    }

    if ( $query->is_search && $query->is_main_query() ) {
        $post_types = get_post_types( array(), 'names' );                   // With no arguments, this should never be empty
        if( ! empty( $post_types ) ) {                                      // But let's check just to be safe!
            $pt_exclude = array( 'attachment', 'revision', 'nav_menu_item' );
            $pt_include = array_diff( $post_types, $pt_exclude );

            $query->set( 'post_type', $pt_include );
        }
    }
}
add_action( 'pre_get_posts', 'search_post_types' );
2
  • Thanks. Should it be $query->is_search ?
    – codecowboy
    Commented Apr 28, 2015 at 16:05
  • @codecowboy You're right good catch! I've updated my answer.
    – Howdy_McGee
    Commented Apr 28, 2015 at 16:09
0

One option is to use the pre_get_posts hook and check that the query is a search query:

function my_theme_pre_get_posts( WP_Query $query ) {
    if ( $query->is_search ) {
        ...
    }

    return $query;
}

add_filter( 'pre_get_posts', 'my_theme_pre_get_posts' );
1
  • 1
    pre_get_posts is an action. From core code do_action_ref_array( 'pre_get_posts', array( &$this ) );. You also don't need to return the variable in an action :-) Commented Apr 28, 2015 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.