Home > Software engineering >  woocommerce_product_query doesn't work on products category page
woocommerce_product_query doesn't work on products category page

Time:10-22

I have custom filters, based on URL params in my woocommerce shop. In functions.php I have something like this:

add_action( 'woocommerce_product_query', 'filtry1' );
function filtry1( $q ){ 
   $meta_query = $q->get( 'meta_query' );
   $meta_query[] = array(
   'key' => 'my_custom_key',
   'value' => $_GET['my_custom_key'],
   'compare' => '=='
);  
$q->set( 'meta_query', $meta_query ); }

And this works great on main shop page. I see additional meta_query in last query.

SELECT mysite_posts.ID FROM mysite_posts INNER JOIN mysite_postmeta ON ( mysite_posts.ID = mysite_postmeta.post_id ) WHERE 1=1 AND ( mysite_posts.ID NOT IN ( SELECT object_id FROM mysite_term_relationships WHERE term_taxonomy_id IN (7) ) ) AND ( ( mysite_postmeta.meta_key = 'my_custom_key' AND mysite_postmeta.meta_value = 'VALUE-FROM-$GET' ) ) AND mysite_posts.post_type = 'acf-field' AND ((mysite_posts.post_status = 'publish')) AND mysite_posts.post_name = 'field_61729c0b8644a' GROUP BY mysite_posts.ID ORDER BY mysite_posts.menu_order ASC, mysite_posts.post_title ASC LIMIT 0, 1 

But if we are in category page then this query doesn't work. Query looks just like this:

SELECT mysite_posts.* FROM mysite_posts WHERE ID IN (86) 

CodePudding user response:

You can use pre_get_posts action hook. it works for both the shop and category pages.

function filtry1($query) {
    if( ! is_admin() && $query->is_main_query() && $query->query_vars['post_type'] == 'product') {
        $query->set( 'meta_query', array (
            array(
                'key' => 'my_custom_key',
                'value' => $_GET['my_custom_key'],
                'compare' => '=='
            )
        ));
    }
}
add_action( 'pre_get_posts', 'filtry1' );
  • Related