How to extract a single value from the array returned by wp_get_post_terms

In WordPress I want to display the term attached to a post in the taxonomy ‘chapters’].
I can get the taxonomy information for a post using

$sectiondata = wp_get_post_terms($post->ID, 'chapters', array("fields" => "all"));

Then using

Read More
print_r $sectiondata;

I can display the array of values returned.

However, how do I echo the value for the ‘name’ of the term to the page?
I thought this should be something like:

echo $sectiondata->name;

But that returns nothing so I obviously don’t understand how to extract this value from the array. I’ve searched around for examples and don’t see anything that explains how to display the value on the page, or perhaps better stated how to extract the value from the array. I’ve tried using the plain php approach of

print($sectiondata['name']);

But that doesn’t return anything either.

Where can I find an explanation of how to extract the value from the array.

Related posts

Leave a Reply

1 comment

  1. The issue is you’re not looping through the array returned. Before I show you how to do this with wp_get_post_terms, have you tried using the get_terms function? I believe this may be a better approach for you:

    $terms = get_terms('chapters');
    echo '<ul>';
    foreach ($terms as $term) {
        echo '<li><a href="'.get_term_link($term->slug, 'species').'">'.$term->name.'</a></li>';
    }
    echo '</ul>';
    

    Source: http://codex.wordpress.org/Function_Reference/get_terms

    If that doesn’t work for you check out how you can use wp_get_post_terms to do pretty much the same thing:

    echo "<ul>";
    $terms = wp_get_post_terms( $post->ID, 'chapters');
    foreach($terms as $term) {
        echo "<li><a href='".get_term_link($term)."' title='".$term->name."'>".$term->name."</a></li>";
    }
    echo "</ul>"; 
    

    http://codex.wordpress.org/Function_Reference/wp_get_post_terms

    I hope this helps you out! Let me know if there’s any issue with either code example above.