You are a victim of WordPress’ great naming scheme. You don’t need get_terms()
, but get_the_terms()
. Note the the
? That makes a huge difference.
-
get_terms( $taxonomies, $args="" )
: Retrieve the terms in a given taxonomy or list of taxonomies. All terms. -
get_the_terms( $id, $taxonomy )
: Retrieve the terms of the taxonomy that are attached to the post. Only the terms for that post.
Now try something like this in a loop:
$terms = get_the_terms( get_the_ID(), 'category' );
print '<pre>'
. htmlspecialchars(
print_r( $terms, TRUE ),
ENT_QUOTES,
'utf-8',
FALSE
)
. '</pre>';
Sample result:
Array
(
[4] => stdClass Object
(
[term_id] => 4
[name] => aciform
[slug] => aciform
[term_group] => 0
[term_taxonomy_id] => 4
[taxonomy] => category
Posts in loop displaying all taxonomies =>
[parent] => 0
[count] => 2
[object_id] => 188
[cat_ID] => 4
[category_count] => 2
[category_description] =>
[cat_name] => aciform
[category_nicename] => aciform
[category_parent] => 0
)
[10] => stdClass Object
(
[term_id] => 10
[name] => Cat A
[slug] => cat-a
[term_group] => 0
[term_taxonomy_id] => 11
[taxonomy] => category
Posts in loop displaying all taxonomies =>
[parent] => 0
[count] => 2
[object_id] => 188
[cat_ID] => 10
[category_count] => 2
[category_description] =>
[cat_name] => Cat A
[category_nicename] => cat-a
[category_parent] => 0
)
)
Now you can iterate over that array and use esc_html( $term->name )
.