Can't retrieve terms name from term object with wordpress terms getter

Issue

So i’ve been trying to get an article term name and I succeeded in getting a every terms attached to every posts i wanted to get with this code below.

how i got the post & then the terms

$recent_posts = wp_get_recent_posts(array(
    'numberposts' => 5,
    'category' => 18,
    'post_status' => 'publish'
));
foreach ($recent_posts as $post_item) {
    var_dump(wp_get_post_terms($post_item['ID'][0]))
}

the returned object of terms I need the [0] to access the object being in an Array


object(WP_Term)#11524 (10) {
    ["term_id"]=> int(31)
    ["name"]=> string(8) "festival"
    ["slug"]=> string(8) "festival"
    ["term_group"]=> int(0) 
    ["term_taxonomy_id"]=> int(31) 
    ["taxonomy"]=> string(8) "post_tag"
    ["description"]=> string(0) "" 
    ["parent"]=> int(0) 
    ["count"]=> int(1) 
    ["filter"]=> string(3) "raw" 
}

However while trying to get the term name and after checking the wordpress codex for a getter
i "found" that we needed to use the getter as either:

$post_item['ID'][0]::__get('name');

or

$post_item['ID'][0]->__get('name);

But both of them produce a critical error while being on the codex.
So my question would be, how would you call that getter other than how I did & why

Solution

You are trying to access the wrong value. It would appear you want this?

foreach ($recent_posts as $post_item) {
    $terms = wp_get_post_terms( $post_item['ID'] );
    $name_of_first_term = $terms[0]->name;
}

Answered By – Howard E

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published