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;


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

6 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?

    • Maybe:
      if( ! is_admin() && $query->is_search && isset( $query->query_vars[‘s’] ) && ! empty( $query->query_vars[‘s’] ) )

  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.

  3. Don’t forget the product visibility in search:

    * Always search for products in search
    add_filter( ‘pre_get_posts’, function( $query ) {
    global $woocommerce;

    if ( ! is_admin() && $query->is_search && isset( $query->query_vars[‘s’] ) ) {
    $query->set( ‘post_type’, ‘product’ );
    $query->set( ‘wc_query’, ‘product_query’ );

    $tax_query = $query->get( ‘tax_query’ ) ?: [];
    $tax_query[] = [
    ‘taxonomy’ => ‘product_visibility’,
    ‘field’ => ‘slug’,
    ‘terms’ => ‘exclude-from-search’,
    ‘operator’ => ‘NOT IN’

    $query->set( ‘tax_query’, $tax_query );

    return $query;
    } );


Leave a Reply