1

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!

1 Answer 1

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;
2
  • Hello – thank you for your answer. As you can see I posted this question a very long time ago and unfortunately I don't think I'll be able to verify whether your suggestion solves my problem. Should I mark your answer as the correct solution anyway? I'm keen for this be as helpful as possible to anyone finding this. If any moderator cares to chime in please let me know how to proceed! Thank you.
    – Simon
    Commented Nov 5, 2020 at 21:32
  • i know :) but i stumbled upon that issue again (the first and only upvote for that question was from me, but some time ago i guess). the answer is finding, what you are looking for, but if it doesnt help you, i wouldnt vote at all. dont worry..
    – honk31
    Commented Nov 6, 2020 at 8:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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