Have Search Only show Specific Post Categories

I want my homepage search bar to only return search results for a specific post category.

How can I do this?

Hi @dstro003,

Unfortunately, it is not possible to modify the search for Home Page only. Still, you can check the following thread which might help you with this.

Thanks

Okay no problem.

Is it possible to set the search results to only display certain categories?

What would be the code that I need to add to the functions.php for this?

Thanks

Hi @dstro003,

You can set the category ids in the Search Query to select the content from specific categories only. You can add the following code into the functions.php of your child theme.

function wpb_search_filter( $query ) 
{
    if ( $query->is_search() && !is_admin() )
    {
        $query->set( 'cat', '4, 8, 12'); //change category 
    }
    return $query;
    
}

Please remember that the above code will work if copied as it is and doesn’t conflict with any existing style.
Please note that the code provided serves only as a guide to help you get started custom coding on your own if there’s no option offered in our theme or the products we bundle.
We really do not provide support for custom codes which means we can’t fix it in case it conflicts with something on your site nor will we enhance it. Further customization should be directed to a third-party developer or you can avail of One, where we answer the questions beyond normal theme support.

Thanks

I added the code to the functions.php child theme and tested it with on category ID 41 “Bit crushers” that only had 7 posts.

This didn’t work. All my websites posts and pages showed up.

Am I doing something wrong here?

Hi @dstro003,

Unfortunately, by mistake, I missed out to add the Hook that calls the function shown in my reply. The code will look like the following.

add_filter( 'pre_get_posts', 'wpb_search_filter' );
function wpb_search_filter( $query ) 
{
    if ( $query->is_search() && !is_admin() )
    {
        $query->set( 'cat', '41'); //change category 
    }
    return $query;
    
}

Hope it helps.
Thanks

Great! Thanks. This worked!

You’re welcome, @dstro003.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.