skip to Main Content

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,
) );

2

Answers


  1. 5 months ago but maybe it will help someone : I’m facing the same issue and all I found is to make a foreach to unset the empties values.

    foreach ($terms as $key => $term) {
        $args = array(
            'post_type' => 'product',
            'paged' => 1,
            'posts_per_page' => 1,
            'order' => 'DESC',
            'post_status' => 'publish',
            'orderby' => 'publish_date',
            'meta_query' => array( array(
                'key' => '_stock_status',
                'value'    => 'instock',
            ) ),
            'tax_query' => array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'id',
                    'terms' => $term->term_id
                )
            )
    
        );
        $loop = new WP_Query( $args );
        if($loop->post_count < 1) {
            unset($terms[$key]);
        }
    }
    
    Login or Signup to reply.
  2. I’ve recently faced the same issue and ended up doing a native query with $wpdb

    Here it is for anyone who needs it:

    SELECT wp_terms.term_id, wp_terms.name, wp_term_taxonomy.parent, wp_terms.term_order 
    FROM wp_terms
    JOIN wp_term_taxonomy 
        ON wp_term_taxonomy.term_id = wp_terms.term_id
    JOIN wp_term_relationships
        ON wp_term_relationships.term_taxonomy_id = wp_terms.term_id
    JOIN wp_posts
        ON wp_posts.ID = wp_term_relationships.object_id
    JOIN wp_postmeta 
        ON wp_postmeta.post_id = wp_posts.ID 
        AND wp_postmeta.meta_key = '_stock_status'
    WHERE wp_term_taxonomy.taxonomy = 'product_cat'
        AND wp_postmeta.meta_value = 'instock'
    GROUP BY wp_terms.term_id
    ORDER BY wp_terms.term_order
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search