How to limit search results to WooCommerce products

WordPress’ default search will return all of the pages, posts, and products that match the specified search phrase. This snippet will filter search results so that only WooCommerce products are shown.

Mixing posts, pages and products in search results can be problematic for a couple of reasons:

  1.  Customers searching in an online store will expect their search to find products they can buy.
  2.  Page layouts designed for products can break when they’re used to display posts and pages.

The easiest solution is to change WordPress’ search function so that it only shows products.

To exclude non-Products from search results, just add the following code snippet to your functions.php file. Make sure you’re using a child theme, otherwise any changes you make will be lost next time your theme updates.

//Only show products in the front-end search results
function lw_search_filter_pages($query) {
if ($query->is_search) {
$query->set('post_type', 'product');
$query->set( 'wc_query', 'product_query' );
}
return $query;
}

add_filter('pre_get_posts','lw_search_filter_pages');

Once this code snippet has been added, only WooCommerce products will be searchable on your site.

Shane Gowland

Hi! I’m a web designer, software developer, and digital marketer based in South Australia. I've been building websites on WordPress for over 12 years. You can learn more about the projects and businesses I'm involved with on my website.

3 thoughts on “How to limit search results to WooCommerce products”

  1. This affects search queries in the dashboard. When !is_admin() is added it fixes most scenarios. However, when trying to add links to other content through the link anchor icon in a Gutenberg Text block, the search results are still limited here. Any idea how to overcome this?

    Reply
  2. The solution is simple if your search form is hard codded, don’t add the filter on the functions page.
    Just add the filter before the front end search form “add_filter()” and remove the filter “remove_filter()” after the search snippet.

    Reply

Leave a Reply