admin管理员组文章数量:1122832
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!
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!
Share Improve this question asked Apr 24, 2017 at 17:50 SimonSimon 313 bronze badges1 Answer
Reset to default 0you are not showing $quantity
, maybe that is off?
this one here definitely works:
$args = [
'post_type' => 'product_variation',
'posts_per_page' => 100,
'meta_query' => [
[
'key' => '_stock',
'value' => 0,
'compare' => '>',
'type' => 'NUMERIC'
]
]
];
$query = new WP_Query($args);
with this query, you get all variations, that are in stock. from there you can get the parent by post_parent ID via get_post_field('post_parent')
if ($query->have_posts()) :
echo '<ul>';
while ($query->have_posts()) :
$query->the_post();
echo '<li>' . get_the_title() . ': ' . get_post_meta(get_the_ID(), '_stock') . ', ' . get_post_field('post_parent') . '</li>';
endwhile;
echo '</ul>';
wp_reset_postdata();
else :
echo '<pre>nothing found</pre>';
endif;
本文标签: meta queryFiltering variable WooCommerce products by stock level using metaquery
版权声明:本文标题:meta query - Filtering variable WooCommerce products by stock level using meta_query 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736292156a1928874.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论