To load a taxonomy term programatically you can use EntityFieldQuery
.
<?php
// Get taxonomy term by field value
$section_vocab = taxonomy_vocabulary_machine_name_load('section');
if($section_vocab) {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'taxonomy_term')
->propertyCondition('vid', $section_vocab->vid);
$result = $query->execute();
...
}
However, that doesn't load the taxonomy term fields. Adding a field condition to the query$query->fieldCondition('field_id', 'value', '123');
to the query doesn't work as the result is always empty.
Bad solution
So the solution using EntityFieldQuery that I found here https://www.drupal.org/node/1517744 works, but it requires looping through all the terms in the vocabulary (in the worst case) which has a high cost.
<?php
// Get taxonomy term by field value
$section_vocab = taxonomy_vocabulary_machine_name_load('section');
$sectionID = NULL;
if($section_vocab) {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'taxonomy_term')
->propertyCondition('vid', $section_vocab->vid)
$result = $query->execute();
if (!empty($result['taxonomy_term'])) {
// To load all terms.
$terms = taxonomy_term_load_multiple(array_keys($result['taxonomy_term']));
// Look up for the first term with the field value that we want.
foreach ($terms as $term) {
// Stop looking if we find it
$value = $term->field_id['und'][0]['value'];
if ($value == $IDtoFind){
$termID = $term->tid;
break;
}
}
}
}
If the taxonomy term has a field with machine field_id
, how can you load the taxonomy terms with a specific value for it?
EntityFieldQuery
in drupal.org/node/1517744.