Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Taxonomy Term ID by Node in Drupal 8

Tags:

drupal-8

I'm trying to get Taxonomy data by particular node.

How can I get Taxonomy Term Id by using Node object ?

Drupal ver. 8.3.6

like image 718
Arfeen Avatar asked Dec 14 '22 21:12

Arfeen


2 Answers

You could do something like that:

$termId = $node->get('field_yourfield')->target_id;

Then you can load the term with

Term::load($termId);

Hope this helps.

like image 153
exit Avatar answered Dec 24 '22 23:12

exit


If you want to get Taxonomy Term data you can use this code:

$node->get('field_yourfield')->referencedEntities();

Hope it will be useful for you.

PS: If you need just Term's id you can use this:

$node->get('field_yourfield')->getValue();

You will get something like this:

[0 => ['target_id' => 23], 1 => ['target_id'] => 25]

In example my field has 2 referenced taxonomy terms. Thanks!

like image 34
wau Avatar answered Dec 24 '22 23:12

wau