Is it possible in WordPress to test for an empty term or category?

I have a project that requires me to list out the available terms for each custom post type and indicate visually which of the terms/categories are empty via css/javascript. Is there a way to return a list of terms/categories and say add a class to the empty ones ? Thanks for any and all assistance.

Related posts

2 comments

  1. Yes there is. First you get your terms using get_terms() (I’m assuming your cpt has associated taxonomy with it)

    <?php 
    
    $custom_terms = get_terms('my_taxonomy');
    
    if (is_array($custom_terms) && !empty($custom_terms)) {
        # code what you want here...
    } else{
        # code if your terms come empty...
    }
    

    This should do it.

    EDIT

    After $custom_terms variable do a print_r($custom_terms); to see what the variable holds. You should get an array filled with stdClass Objects, one for each category in this taxonomy.

    So you can further do something like this:

    foreach ($custom_terms as $term) {
        if ($term->count != 0) {
            print_r($term->name);
        }
    }
    

    This will show you names of non empty categories in your taxonomy.

  2. Here is how to query the terms with the WP_Term_Query class (to complement dingo_d’s answer):

    $args = array(
     'taxonomy'   => 'my_taxonomy',
     'hide_empty' => false
    );
    $custom_terms = new WP_Term_Query($args);
    

    Then, this would be how to iterate over the terms:

    foreach($custom_terms->terms as $term){
        if ($term->count != 0) {
            print_r($term->name);
        }
    }
    

    This is a very short and concise article on why you should now use WP_Term_Query:

    https://medium.com/vunamhung/say-goodbye-to-get-terms-use-wp-term-query-db774df6d9ea

Comments are closed.