Filtering search results

I have pages, posts and woocommerce product categories and products in my website. I want to limit wordpress default search query so that it returns the posts, the pages, the product categories but NOT individual products. I am using the following code in my functions.php with which I can easily show only posts and pages. What I need now, is to show the woocommerce product categories along with my posts and pages in the search result, but NOT the individual products. Please help me out here.

function searchfilter($query) {

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

return $query;
}

add_filter('pre_get_posts','searchfilter');

2 Answers
2

You may need to include a tax_query for the Woocommerce taxonomy (called ‘product_cat’):

    $tax_query = array(
        array(
            'taxonomy' => 'product_cat'
        ),
    );
    $query->set( 'tax_query', $tax_query );   
}

return $query;
}

However, you’ll have to ensure that you can return posts AND pages AND product categories and also note the search results will be mixed up together.

I would have thought a better solution, rather than filtering at functions.php level, would be to adapt your search.php for the display of the search results. You can then be quite targeted, for instance show:

Posts with this search include:
PostX, PostY, PostZ.

And then another loop with:

Pages with this search include:
PageA, PageB, PageC.

And then another loop with:

Product Categories with this search include:
Product Cat A, Product Cat F, Product Cat Z.

Is that the kind of result you are after, or would you like to filter EVERY search on your site and mix up the results?

Leave a Comment