1

I want to display a specific category of products on the top page of the shop page.
This was achieved with the code below.
However, with this code, when searching for products from the search console, only products in the specified category will be searched.
Is it possible to write code that invalidates the code triggered by the search console search action?

add_action('pre_get_posts','shop_filter_cat');

function shop_filter_cat($query) {
if (!is_admin() && is_post_type_archive( 'product' ) && $query->is_main_query()) {
$query->set('tax_query', array(
array ('taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( '#','#'), //
)
)
); 
}
}
0

This seems to be normal behavior since your filter will apply to any query made on post type archive "product". You might be able to deactivate the filter for search query by adding the is_search condition to your filter so your function would look like so:

add_action('pre_get_posts','shop_filter_cat');

function shop_filter_cat($query) {
    if (!is_admin() && is_post_type_archive( 'product' ) && $query->is_main_query() && !is_search()) {
    $query->set('tax_query', array(
        array ('taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array( '#','#'), //
            )
        )
    ); 
    }
}

Untested. hopefully this will help !

Codex ref: https://developer.wordpress.org/reference/functions/is_search/

2
  • Thank you for the answer. Tried and solved! I was really impressed because I was very worried. Thank you very much!
    – LMDM
    Mar 30 '20 at 3:58
  • @LMDM Glad it helps ! If this fixed your problem, would you mind accepting my answer ? Thanks!
    – Gui
    Mar 30 '20 at 4:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.