I am trying to get the taxonomy values associated with my custom post types. I have a function which fetches a post ($object)'s taxonomies, then cycles through the taxonomies and gets the values for that post for each taxonomy. At least, that's what I want it to do! Here it is:

function get_the_categories($object, $field_name, $request) {

  // I've verified that $object['id'] gives same value as $post->ID equivalent

  $taxonomies = get_post_taxonomies( $object[ 'id' ]);

  // ^ returns ["post_tag","member_of","member_type" ]

  $returnArray = array();
  foreach($taxonomies as $taxonomy) {
    $val = wp_get_post_terms( $object['id'], $taxonomy, array(
      'fields' => 'name'
  return $returnArray;

The $taxonomies query returns three strings, which are the names of my two custom taxonomies. However, the wp_get_post_terms query returns an empty array!

Can anyone see what I'm doing wrong?



Just change

'fields' => 'name'


'fields' => 'names'

If you look at the examples in wordpress documentation you can see you should use plural(names, slugs, ids for fields): https://codex.wordpress.org/Function_Reference/wp_get_post_terms#Examples

  • Thanks for that spot, but it hasn't fixed my problem :( I'm still getting a response with empty arrays for each value of my $returnArray – dafyddPrys May 20 '16 at 8:59
  • Yeah, one more thing: wp_get_post_terms returns array itself. So if you want to return first term you should use $returnArray[$taxonomy]=$val[0]; – Nijat Rajabli May 20 '16 at 9:03
  • Unfortunately I've tried that too: I added $val = isset($val[0]) ? $val[0] : null; before assigning $val to the array and I just get nulls as values for each array item. – dafyddPrys May 20 '16 at 9:06
  • Do you get any value when you write echo $val = wp_get_post_terms( 1234, 'book', array( 'fields' => 'names' ));? With specific post that you know has taxonomies. One reason can be that you havn't create a relationship between taxonomy and post or post type. Another can be the post that you are testing has not any taxonomy term. Just try these and let us know. – Nijat Rajabli May 20 '16 at 9:15
  • That returns an empty array as well (with my own values).. I was wondering if I have associated the taxonomies properly. I have used the register_taxonomy function in the 'init' hook and I can see the custom taxonomies in the admin GUI.. Could anything else be needed? The taxonomy values (eg member_type has 'media', 'race' as options) were all added in the GUI and these are what I'm trying to access. – dafyddPrys May 20 '16 at 9:25

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.