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

混江龙づ霸主 提交于 2019-12-08 03:25:57

问题


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.


回答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.



来源:https://stackoverflow.com/questions/33098900/is-it-possible-in-wordpress-to-test-for-an-empty-term-or-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!