18

What function will display custom taxonomies associated with a post as text?

I'm currently using get_the_term_list which works great for a singular page but not so much when using a taxonomy in the archive-postype.php permalink title tag.

5 Answers 5

18

wp_get_object_terms() returns the terms associated with an object (eg a post or a page or custom post) as text (normally in an array).

From the Codex page for wp_get_object_terms()

$productcategories = wp_get_object_terms($post->ID, 'productcategories');

1
  • Keep in mind that the query results aren't cached like get_the_terms(). See the codex page for info.
    – Dylan
    Sep 8, 2016 at 4:25
24

However @anu is right, I figured out you can call the php function strip_tags to strip out the tags of the return value.

$terms = get_the_term_list( $post->ID, 'tags' );
$terms = strip_tags( $terms );
2
  • Looks so simple and does the job. Is there any downside using this? Jan 3, 2017 at 13:11
  • @Mohsin One downside is that it strips all tags, not just the <a> tag. However, you can prevent desired tags from being stripped, like so: $terms = strip_tags( $terms, '<li>' );
    – David
    Dec 6, 2017 at 8:20
3
$terms = wp_list_pluck( get_the_terms( get_the_ID(), 'your_taxonomy' ), 'name');

Here $terms is an array, so you can use a foreach loop.

foreach( $terms as $term ) {
  echo $term;
}
3

I think the best way is to implement a filter for the term list, that extract via regexp only the text, from the list

See get_the_terms_list() and the Hook in Developer Resources.

 $term_links = apply_filters( "term_links-{$taxonomy}", string[] $links ) 

You can implement your own filter.

1
  • That's exactly the hook I found by reading the source code.
    – wittich
    Feb 2 at 7:57
1

I need the same and tried Zack solution that works great. For instance, if you need onlye the term to put in css id or class. Only one anotation about the solution, the function is bad called, properly is "get_the_term_list".

I show my example:

$terms = get_the_term_list( $post->ID, 'your_taxonomy_name' );
$terms = strip_tags( $terms );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.