问题
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 Object
s, 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