WP Query - Get WooCommerce Products with variation that is in stock

admin2025-06-02  1

I am creating a clothing store. The clothing are variable products based on size (xs, s, m, l, xl etc..). I am trying to create filters to display products that are in stock, based on a filter. So, clicking the "xs" filter should show products that both have the XS variation, and have that variation in stock.

So far, I've got something like this:

$query_args = array(
 'post_type' => 'product', 'product_variation',
 'posts_per_page' => 12,
 'paged' => $paged,
 'tax_query' => array(
    array(
    'taxonomy' => 'pa_sizes',
    'field' => 'term_id',
    'terms' => 'xs',
    ),
 ),
 'meta_query' => array(
    array(
    'key' => '_stock_status',
    'value' => 'outofstock',
    'compare' => '='
    ),
 )
);

$query = new WP_Query($query_args);

I know right now it's searching for "outofstock" but that was just a test, and not even this comes up with any products, even though I have created some products with some sizes out of stock.

I am creating a clothing store. The clothing are variable products based on size (xs, s, m, l, xl etc..). I am trying to create filters to display products that are in stock, based on a filter. So, clicking the "xs" filter should show products that both have the XS variation, and have that variation in stock.

So far, I've got something like this:

$query_args = array(
 'post_type' => 'product', 'product_variation',
 'posts_per_page' => 12,
 'paged' => $paged,
 'tax_query' => array(
    array(
    'taxonomy' => 'pa_sizes',
    'field' => 'term_id',
    'terms' => 'xs',
    ),
 ),
 'meta_query' => array(
    array(
    'key' => '_stock_status',
    'value' => 'outofstock',
    'compare' => '='
    ),
 )
);

$query = new WP_Query($query_args);

I know right now it's searching for "outofstock" but that was just a test, and not even this comes up with any products, even though I have created some products with some sizes out of stock.

Share Improve this question asked Mar 17, 2018 at 1:37 Jordan CarterJordan Carter 2912 gold badges5 silver badges13 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

You will have to change your tax_query. The xs is not the term_id but the slug

So your tax_query will end up being like

'tax_query' => array(
    array(
       'taxonomy' => 'pa_sizes',
       'field' => 'slug',
       'terms' => 'xs'
    )
 )

I would love to help with the "instock" problem too, but I'm stuck with that question too.

Isn't this way correct?

'post_type' => array('product', 'product_variation'),

Your $query_args is broken array

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748852624a314260.html

最新回复(0)