Filtering variable WooCommerce products by stock level using meta_query

Question

I’m trying to filter the products on my shop page based on stock level by adding a condition to the meta query. For variable products I get zero results, but simple products work.

I’m running the following in the woocommerce_product_query hook:

$metaQuery = $q->get('meta_query');
$metaQuery[] = array(
  'key' => '_stock',
  'value' => $quantity,
  'compare' => '>='
);
$q->set( 'meta_query', $metaQuery );

I tried explicitly adding variations to the query, but it didn’t seem to make a difference:

$q->set( 'post_type', array('product', 'product_variation') );

Any ideas where I’m going wrong? Grateful for any help!

0
Simon 2 months 0 Answers 11 views 0

Leave an answer