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.

Leave a Reply