Retrieve Taxonomy Term by a custom field

Starting with Drupal7, once can add fields to taxonomy terms.

This can be interesting to add images or other informations. But what if you want to search a taxonomy term on this custom field in a module ?

Imagine we have a list of Music Categories, and we add a custom field, "music_code", that is used to interface with one other system.

Then we have 2 options :

In this article, I explain how to retreive a term ID based on a custom field on a Drupal taxonomy.

This example can be run on the command line for testing, no need for a module.


// drupal bootstrap
$drupal_directory = "/var/www/drupal";
define('DRUPAL_ROOT', getcwd());
require_once './includes/';

// Retrieve Vocabulary ID (VID)
$vocab = taxonomy_vocabulary_machine_name_load($vocabulary_name);

// bundle = Machine Name of the vocabulary
$query = new EntityFieldQuery();
  ->entityCondition('entity_type', 'taxonomy_term')
  ->entityCondition('bundle', $vocabulary_name)
  ->propertyCondition('vid', $vocab->vid)
  ->fieldCondition('field_music_code', 'value', 'C042', '=');

$results = $query->execute();
if (!empty($results['taxonomy_term'])) {
  foreach($results['taxonomy_term'] as $tid) {
    $term = taxonomy_term_load($tid->tid);
    echo "Term ID = ",$term->tid," Name = ",$name,PHP_EOL;
    echo "Field Code Client Value = ",$term->field_music_code[LANGUAGE_NONE][0]['value'],PHP_EOL;
  echo "No result for this code ! ",PHP_EOL;

The first lines are here only to bootstrap Drupal when you are not in a module.

Then we define the Vocabulary ID, with taxonomy_vocabulary_machine_name_load function. This gives us the vocabulary ID (we suppose it is created).

Then we build the Entity Query, with several parameters :

  • Entity type : in our case, it is 'taxonomy_term' because we are dealing with taxonomies
  • Bundle : the machine name of our vocabulary
  • propertyCondition : the vocabulary ID we use to identify the terms (belonging to this vocabulary)
  • fieldCondition : the condition placed on the custom field.

In this example, the code is C042, and we search all terms (well, there is only one) that is using this code.

The result in our case is :

Term ID = 4 Name = Funk
Field Code Client Value = C042