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 badges
Add a comment  | 

1 Answer 1

Reset to default 0

you 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