Drupal - How to get the term Id from a name with the taxonomy_get_term_by_name

I tried using the following code to get termId from the term:

$term = taxonomy_get_term_by_name($address_string); $termId = $term[0]->tid; 

There is 1 result, but it appears as a term [30] - therefore the above code does not work.

I thought I could access the array of terms by looking at the first element - for example. $ Term [0]

What am I doing wrong?

Here is the result of var_dump ($ term):


 array (size=1) 30 => object(stdClass)[270] public 'tid' => string '30' (length=2) public 'vid' => string '4' (length=1) public 'name' => string 'Thonglor' (length=8) public 'description' => string '' (length=0) public 'format' => string 'filtered_html' (length=13) public 'weight' => string '0' (length=1) public 'vocabulary_machine_name' => string 'areas' (length=5) 

Thank you very much,

Pw

+4
source share
1 answer

Probably the best option would be

 $termid = key($term); 

He will output 30

http://php.net/manual/en/function.key.php

The key () function simply returns the key of the array element that the internal pointer points to. It does not move the pointer in any way. If the internal pointer points outside the list of elements or the array is empty, key () returns NULL.

Better call

 reset($term); 

before calling a key function

Reset reset pointer of the internal array to the first element

Another option is that the Drupal API Guide says itself, https://api.drupal.org/comment/18909#comment-18909

 /** * Helper function to dynamically get the tid from the term_name * * @param $term_name Term name * @param $vocabulary_name Name of the vocabulary to search the term in * * @return Term id of the found term or else FALSE */ function _get_term_from_name($term_name, $vocabulary_name) { if ($vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name)) { $tree = taxonomy_get_tree($vocabulary->vid); foreach ($tree as $term) { if ($term->name == $term_name) { return $term->tid; } } } return FALSE; } 
+6
source

Source: https://habr.com/ru/post/1493188/


All Articles