John Davidson

php - WooCommerce: Show only terms with products in stock

0 comments
Message:


I'm using get_terms to show a list of terms. It works fine so far.
But I want to hide every term with out of stock products.
If I use 'hide_empty' => true it wouldn't work because the products are there and published.


Is there a way to add the _stock meta field to the get_terms function?
Unfortunately I have to use get_terms.


Here's my code (it's a lot bigger but that's the part):


$terms = get_terms( array(
'taxonomy' => 'product_tax',
'orderby' => 'name',
'hide_empty' => true,
) );


My Answer:
false in get_terms, it will show all terms regardless of whether they have products in stock or not.

To only show terms with products in stock, you can use the 'meta_query' parameter in get_terms to filter out terms with out of stock products. Here's an example code snippet:

php
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
'meta_query' => array(
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '='
)
)
) );

foreach ( $terms as $term ) {
echo '' . $term->name . '
';
}


In this code snippet, we are querying for terms in the 'product_cat' taxonomy that have products in stock (with '_stock_status' meta key set to 'instock'). Only terms with products in stock will be displayed in the list.

Rate this post

3 of 5 based on 7555 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us