I have a custom post type called user_images
. I would like to create some filters and populate the dropdowns dynamically. I am using the follow code:
$post_type="user_images";
$taxonomies = get_object_taxonomies((object) array('post_type' => $post_type));
$terms = get_terms('image_categories');
foreach( $terms as $term ){
echo $term->name;
}
This is correctly listing my custom taxonomy Image Categories
but it is showing terms even if none of the posts have that term assigned to it. How can I only list out the terms which are associated with posts and within this specific custom post type?
1 Answer
get_terms
should hide empty terms by default, but you can force it to setting hide_empty
argument to true:
$terms = get_terms( array(
'taxonomy' => 'image_categories',
'hide_empty' => false,
) );