I need to get the id of the node category.

I try this:

$variables['tid'] = $node->field_category->target_id;

I wrote this answer thinking the question was for Drupal 7. This is not accurate for Drupal 8.

If you debug the $node object, you will see that it's more complicated than that. It has a language and probably a value index. So, you could access the TID this way:

$variables['tid'] = $node->field_category[LANGUAGE_NONE][0]['target_id'];

But, don't do it that way. It would be better to use EntityMetadataWrapper. The code should look something like this:

$wrapper = entity_metadata_wrapper('node', $node);
$variables['tid'] = $wrapper->field_category->raw();

If you want the whole term object, you can do this:

$variables['term'] = $wrapper->field_category->value();
  • entity_metadata_wrapper is a Drupal 7 thing, it can't be used in Drupal 8 (mainly because it's obsolete) – Clive Mar 23 '17 at 14:39
  • I didn't notice that the question was for Drupal 8. I will clarify my response. – Wayne Eaker Mar 24 '17 at 13:31

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.