Search code examples
phpwordpresssearchwoocommerceproduct

Limit search results to WooCommerce Products only in frontend


Background:

I would like to limit the search results to show only WooCommerce Products. This code below does exactly what I want.

//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');

Problem:

By using the code above, it affects how some of the plugins on my site work. For example, in Elementor Pro, when I am searching for the Checkout Page, it will not show up. Instead, only Products show up. Example screenshot:

enter image description here

Is there a way to resolve this?


Solution

  • Using ! is_admin() will limit this filter to frontend only to avoid many problems on backend:

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