I am using WordPress' native function get_the_terms and it returns this array with an object inside:
array (size=2)
157 =>
object(stdClass)[41]
public 'term_id' => int 157
public 'name' => string 'Entertainment' (length=13)
public 'slug' => string 'entertainment' (length=13)
public 'term_group' => int 0
public 'term_taxonomy_id' => int 157
public 'taxonomy' => string 'category' (length=8)
public 'description' => string '' (length=0)
public 'parent' => int 0
public 'count' => int 1
public 'object_id' => int 644
public 'filter' => string 'raw' (length=3)
151 =>
object(stdClass)[40]
public 'term_id' => int 151
public 'name' => string 'Featured' (length=8)
public 'slug' => string 'featured' (length=8)
public 'term_group' => int 0
public 'term_taxonomy_id' => int 151
public 'taxonomy' => string 'category' (length=8)
public 'description' => string '' (length=0)
public 'parent' => int 0
public 'count' => int 1
public 'object_id' => int 644
public 'filter' => string 'raw' (length=3)
How do I access
public 'name' => string 'Featured' (length=8)
This works
$terms = get_the_terms( $post->ID, 'category' );
foreach ($terms as $term) {
$test = $term->name;
echo $test;
}
This does not work:
for($i=1; $i<3; $i++) {
$term = $terms->name;
echo $term;
}
nor does this work
for($i=1; $i<3; $i++) {
$term = $terms[0]->name;
//$term = $terms[1]->name;
//$term = $terms[157]->name; // works but not reliable
echo $term;
}
Why?
$term = $terms[$i]->name;