0

I know I can get an array of term objects with this line:

$terms = wp_get_post_terms($post->ID, 'mytaxonomy', array('fields' => 'all'));

Or, I can get a simple array of term names with this:

$term_names = wp_get_post_terms($post->ID, 'mytaxonomy', array('fields' => 'names'));

But I don't know how to extract just the names from the array of objects ($terms). This is so I don't have to call wp_get_post_terms several times.

  • You are correct about names. $term_names = wp_get_post_terms($post->ID, 'mytaxonomy', array('fields' => 'names')); works and retrieve an array of term names – Pieter Goosen Oct 14 '15 at 19:05
1

$terms is an array of objects. You must select one of the array entries before you can reference its properties (fields).

This will print the 'name' of the first object (index zero):

if ($terms) {
   echo $terms[0]->name;
}

This will print all the 'name' fields:

if ($terms) {
   foreach( $terms as $term ) 
      echo $term->name;
}
  • That works. I can just make a loop to make a new array with just the names. I thought there might be a simpler way. – photocurio Oct 14 '15 at 18:51
  • 1
    If you found the answer helpful, please accept it. – shanebp Oct 14 '15 at 19:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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