1

I've excluded certain pages from the WP Search with the code below in my functions.php file.

I also need to exclude a custom post type called 'sites'.

I can't seem to find the custom post type equivalent of the post__not_in argument ?

I don't want to remove it in the custom post type code itself under public => false because I still want it to have its own url etc.

Does anyone know how to remove a specific custom post type from showing up in WP Search?

Any help would be wonderful !

// EXCLUDE CERTAIN PAGES FROM SEARCH RESULTS (PAGE IDs IN ARRAY)

function tp_remove_pages( $query ) {
  if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
    $query->set( 'post__not_in', array( 11,84,118,115,123,132 ) );
  }
}
add_action( 'pre_get_posts', 'tp_remove_pages' );
1

1 Answer 1

1

Instead of enumerating page IDs you don't want, you could instead set the post types that you do want.

You can of course combine the 2 approaches if you wish, but below I've included pages, posts, and another type you might want if you have other types on your site.

e.g.:

function tp_remove_pages( $query ) {
  if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
    $query->set( 'post_type', array( 'page', 'post', 'other_custom_type_you_want' ) );
  }
}
add_action( 'pre_get_posts', 'tp_remove_pages' );

EDIT: An alternative to using this code to modify the search behaviour "after the fact", is to change the nature of your custom post types when you register them. To do this, use the exclude_from_search argument when registering your post type.

Ref: https://developer.wordpress.org/reference/functions/register_post_type/

You could also set the public argument to false to achieve a similar result, though this may impact other behaviours of your post type.

2
  • Thanks for this Paul. Is there a 'not_post_type' or equivalent? I have quite a few different pages and custom post types and it would be easier just to exclude the one called 'sites'. Thanks
    – pjk_ok
    Commented May 31, 2020 at 19:02
  • I've edited the answer to include an alternative approach that might get you what you need. There is to "not_post_type" query argument.
    – Paul G.
    Commented Jun 2, 2020 at 10:14

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.