get_terms only show term if there is a post using it

admin2025-06-04  2

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?

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?

Share Improve this question asked Jan 16, 2019 at 16:49 user13286user13286 2272 gold badges13 silver badges29 bronze badges 1
  • Maybe you can look at object_ids and hide_empty of get_terms()? I think there was a similar question here recently but can't seem to find it. – birgire Commented Jan 16, 2019 at 16:57
Add a comment  | 

1 Answer 1

Reset to default 4

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,
) );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749004930a315546.html

最新回复(0)