As a noob in PHP, I'm trying to filter out products in Woocommerce using array. I managed to only filter them by category.
I also would like to filter out ones, that are out of stock and drafts (by array, if possible).
And one more question, how do I add in 'product_cat'
more than one category? When I want to filter hoodies and shirts for example?
For the in stock product I have tried following code, which doesn't work:
'meta_value' => array(
array(
'key' => 'get_stock_status',
'value' => 'outofstock',
'compare' => '!='
)
)
Not sure, how to check if they are drafts or not.
This is my code:
<ul class="products">
<?php
$args = array(
'post_type' => 'product',
'orderby' => 'rand',
'posts_per_page' => 1,
'product_cat' => 'hoodies'
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
woocommerce_get_template_part( 'content', 'product' );
endwhile;
}
wp_reset_postdata();
?>
</ul>
You can check if products are in stock by passing arguments to meta_query
'meta_query' => array(
array(
'key' => '_stock_status',
'value' => 'instock'
)
)
Checking for multiple categories with category__and
you'd need to pass an array of category IDs
'category__and' => array(1,2) // select categories with array of IDs
And to check for posts/products that are published you need to pass publish
to post_status
:
'post_status' => 'publish' // select products that are published
Together it might look something like this (Note: Not tested)
$args = array(
'post_type' => 'product',
'orderby' => 'rand',
'posts_per_page' => 1,
'category__and' => array(1,2), // replace these with your cat IDs
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_stock_status',
'value' => 'instock'
)
)
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
woocommerce_get_template_part( 'content', 'product' );
endwhile;
}
wp_reset_postdata();