Get Post Terms of Current Post (selected taxonomy term) – How to get only the taxonomy value and not "Array ( [0] => taxonomy term )" in the frontend?

Moe asked
custom-post-types custom-field taxonomy
via

I use the get_post_term code from https://codex.wordpress.org/Function_Reference/wp_get_post_terms. I can retrieve the selected taxonomy term from the current post but the displayed value looks like this: Array ( [0] => Taxonomy Term). I only want the taxonomy term in the frontend.

//Returns Array of Term Names for "my_taxonomy" $term_list = wp_get_post_terms($post->ID, 'my_taxonomy', array("fields" => "names")); print_r($term_list);

Does someone know how to only display the selected taxonomy term?


Answer
via

The wp_get_post_terms() function returns one or more term names when you call it with array( 'fields' => 'names' ). So you have a few different options available to you.

Grab the first term name that was found.

<?php
$term_names = wp_get_post_terms($post->ID, 'my_taxonomy', array('fields' => 'names'));

if ( ! empty( $term_names ) ) {
  echo $term_names[0]; // Cats
}

Or, you can implode the list of term names and show them in comma-delimited format.

<?php
$term_names = wp_get_post_terms($post->ID, 'my_taxonomy', array('fields' => 'names'));

echo implode(', ', $term_names); // Cats, Pets, Animals

Or, you can iterate through the list and do something else.

<?php
$term_names = wp_get_post_terms($post->ID, 'my_taxonomy', array('fields' => 'names'));

foreach( $term_names as $name ) {
    echo $name.'<br />';
}
Share This
Posted in: