Get Taxonomy Term ID by Node in Drupal 8

强颜欢笑 提交于 2019-12-10 15:54:16

问题


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


回答1:


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!




回答2:


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.




回答3:


@Kevin Wenger's comment helped me. I'm totally basing this answer on his comment.

In your code, when you have access to a fully loaded \Drupal\node\Entity\Node you can access all the (deeply) nested properties.

In this example, I've got a node which has a taxonomy term field "field_site". The "field_site" term itself has a plain text field "field_site_url_base". In order to get the value of the "field_site_url_base", I can use the following:

$site_base_url = $node->get('field_site')->entity->field_site_url_base->value;



回答4:


How to extract multiple term IDs easily if you know a little Laravel (specifically Collections):

Setup: composer require tightenco/collect to make Collections available in Drupal.

// see @Wau's answer for this first bit...
// remember: if you want the whole Term object, use ->referencedEntities()
$field_value = $node->get('field_yourfield')->getValue();

// then use collections to avoid loops etc.
$targets = collect($field_value)->pluck('target_id')->toArray();

// $targets = [1,2,3...]

or maybe you'd like the term IDs comma-separated? (I used this for programmatically passing contextual filter arguments to a view, which requires , (OR) or + (AND) to specify multiple values.)

$targets = collect($field_value)->implode('target_id', ',');

// $targets = "1,2,3"


来源:https://stackoverflow.com/questions/45693005/get-taxonomy-term-id-by-node-in-drupal-8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!