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?

  • You want the name of the Term? A Term is associated with many properties. Which component are you interested in displaying. I assume the name; e.g., Animals? – jaswrks Nov 5 '17 at 11:21
  • Yes, I want only the name. – Moe Nov 6 '17 at 11:43

It works with this code to show only the name, however the output is displayed in small characters so I only need to capitalize it somehow

<?php // Get terms for post $terms = get_the_terms( $post->ID , 'my_taxonomy' ); // Loop over each item since it's an array if ( $terms != null ){ foreach( $terms as $term ) { // Print the name method from $term which is an OBJECT print $term->slug ; // Get rid of the other data stored in the object, since it's not needed unset($term); } } ?>

Assuming the taxonomy name is "animals"

<?php
    //This will show all the terms in taxonomy whether they have posts or not thus the "hide_empty"
    $terms = get_terms( array ( 'taxonomy' => 'animals', 'hide_empty' => false, 'parent' => 0, 'orderby' => 'description', 'order' => 'ASC' ));

    foreach ($terms as $term) {
        // The $term is an object, so we can get the names.
        //use var_dump($term) to see other options available
        echo $name = $term->name;
    }
?>

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 />';
}

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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