I'm very surprised I can't find an answer anywhere, since this seems to me to be a simple, basic question. How can I get the term id (tid) for a taxonomy term from the term name? That is, for the term itself. I would like to do this in the page.tpl.php file.
I would like to be able to take a taxonomy term such as: MO-10-004
And get the tid, for example: tid = 159
The vocabulary id in this case (vid) is 4.
I guess my real question is, "Is this information already available to me within the page.tpl.php file in an existing variable, which I can access?" And if it is, how do I access it? I'm assuming the taxonomy module has already loaded the term data from the database and put it in a variable somewhere, so I don't want to add another SQL query if it's already been done.
Comments
Where are you getting the
Where are you getting the taxonomy term from? The path, a node, something else?
taxonomy_get_tid_by_name()
taxonomy_get_tid_by_name()
-----------------------------------------
Joep
CompuBase, Dutch Drupal full service agency
Almost right but...
Should be:
taxonomy_get_term_by_name()
http://api.drupal.org/api/function/taxonomy_get_term_by_name/6
attention: This can result in
attention: This can result in multiple returns (array). So if you want to get the tid for "foobar" it could result in an array of tids. In most cases it is not possible to get a unique "termanme id".
taxonomy_get_term_by_name()
taxonomy_get_term_by_name() will return array of terms if there are multiple terms with same names.
You should then iterate through that array and do a conditional check based on other term properties to find a unique one (check for parent ID, vocab ID etc.) However, this doesn't ensure unique match either, as only unique term field is TID.
Example where name is known to be unique
An example where the taxonomy names are known to be unique:
drupalshrek
For D7...
// Get's the tid from term name
$tid = key(taxonomy_get_term_by_name('some term name'));
Alert?
key() function expects to have &$array as param so we can't use it with value that function returns.
Better will be use construction like this
$terms = taxonomy_get_term_by_name('some term name');
$tid = key($terms);
or
$tid = reset($terms)->tid;
P.S. Don't forget to check if function result is not empty
This works.
This worked, cheers. (I only have one instance of the term I'm after, if that's your situation, this will work for you too).
$terms = taxonomy_get_term_by_name('some term name');
$tid = key($terms);
This worked for me. Thanks
This worked for me. Thanks man
Works thanks. Without the key
Works thanks. Without the key you get a bunch of nested array
For Drupal 8:
Load taxonomy term by term name.
For Drupal 9
For drupal 9 get taxanomy id by term name
you can give your vocabulary name and term name.
Thanks