0

I'm looking to hide from search a few custom post type posts. I'm thinking that if I create a custom taxonomy for the custom post type with a term "hidden" then all posts checked will be hidden. Maybe some filter that I can add to the functions file? By chance has anyone done this or something similar? Please advise, thanks in advance :)

Regards, Kendell

2 Answers 2

2

register_post_type() has a argument that you can set to specify which post types you want searched, thus excluded the undesired ones. This is the simplest method, just one line:

'exclude_from_search' = true,

Alternative to that, you can hook into the search query itself via pre_get_posts and then modify the search, specifying which post types you're after:

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

If you were dead set on doing the term hiding - although I don't recommend it, as it's more code with a higher chance of user error - you'd do somthing like:

add_action( 'pre_get_posts', function ( $query ) {
    global $wp_the_query;
    if($query === $wp_the_query && $query->is_search() && !is_admin()) {
        $tax_query = array(
            array(
                'taxonomy' => 'your_custom_tax_name',
                'field' => 'slug',
                'terms' => 'hidden',
                'operator' => 'NOT IN',
            )
        );
        $query->set( 'tax_query', $tax_query );
    }
});
2
  • I added the code snippet to my functions.php and it still returned the custom post type. I also tried the example with the term but to no luck. 'exclude_from_search' = true, would hide all the posts of that custom post type right? Commented Feb 27, 2018 at 1:00
  • It should be 'exclude_from_search' => true,.
    – lowtechsun
    Commented Oct 20, 2019 at 12:56
0

For the sake of anyone else searching for a solution i used the SearchWP plugin to exclude these posts.

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.