Search code examples
phpdrupaldrupal-7drupal-taxonomy

Get a field value from a taxonomy_term the "right way"


I am trying to get the value of various fields from taxonomy terms (and I'd like to do it the right way, i.e. not $term->field_foo['und'][0]['value'])

I'm able to do this reliably for nodes and adapted my method for taxonomy terms, but it doesn't seem to be working. Here is my code:

$field = field_get_items('taxonomy_term', $term, 'field_foo');
$value = field_view_value('taxonomy_term', $term, 'field_foo', $field[0]);
$rendered = render($value);

In troubleshooting this, I can see that field_get_items correctly returns an array... if I insert a var_dump (of $field) after the first line there, i get this:

array (size=1)
  0 => 
    array (size=1)
      'value' => string '1' (length=1)

Yet field_view_value returns an empty string... again a var_dump (of $value) after the second line results in this:

array (size=2)
  '#markup' => string '' (length=0)
  '#access' => boolean true

Can anyone see where I'm going wrong?


Solution

  • You can use the Entity Metadata Wrapper:

    $term = entity_metadata_wrapper('taxonomy_term', TERM_ID);
    

    Simpler and reliable.