xojijog684
xojijog684

Reputation: 310

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?

Upvotes: 4

Views: 7448

Answers (2)

raftaar1191
raftaar1191

Reputation: 373

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

Using ! is_main_query() will limit this filter to work only in the main query

https://gist.github.com/raftaar1191/0ec06e69ffc661e25a7899154b9025c9

Upvotes: 0

LoicTheAztec
LoicTheAztec

Reputation: 253794

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;
}

Upvotes: 9

Related Questions