I have been searching google but I am really confused. I am trying to display the terms of the taxonomy assigned to the post. I am using the_terms($post->ID, 'locations');
. The custom taxonomy is hierarchical.
Example: 3 terms assigned to post: USA(parent) > FL(direct child of "USA") > Miami(direct child of "FL")
. What I get: FL, Miami, USA
which means the terms are being displayed in alphabetical order. I want them to be displayed like: Miami, FL, USA
. Can this be achieved? I would also like to remove the anchors from the terms and strip_tags(the_terms($post->ID, 'locations'))
doesn’t seem to work.
While searching google some people use get_terms()
some other get_the_terms
and others the_terms
which is what I use and seems to work – output the terms. What is the difference between those functions? Am I using the right one?
2 Answers
To answer your first question
What is the difference between those functions
-
get_terms()
returns an array of terms objects that belongs to a specific taxonomy -
get_the_terms()
returns an array of terms belonging to a post -
the_terms()
displays an HTML formatting string of term names belonging to a post
Because you need your terms not hyperlinked and ordered according to parent, I believe wp_get_object_terms()
will be a better option here. wp_get_object_terms()
also returns an array of terms belonging to a post, but is more flexible. You do pay for this flexibility though as you make an extra db call per post.
With this all in mind, you can try the following: (All code is untested)
$args = [
'orderby' => 'parent',
'order' => 'DESC'
];
$terms = wp_get_object_terms( $post->ID, 'locations', $args );
$names = wp_list_pluck( $terms, 'name' );
$output = implode( ', ', $names );
echo $output;