0

In a D7 custom module, I wish to retrieve a taxonomy term by it's description (and not it's name or TID).

Right now I do have it working, but I feel the code is a bit clunky, and I feel like there is a more elegant / Drupally way of doing it.

Is there a better way of doing it then this?

$vocabulary = taxonomy_vocabulary_machine_name_load('my_vocabulary');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));

foreach ($terms as $term) {
  if ($term->description == 'my_term_description') {
    // Do stuff when there is a match.
  }
}

Ideally, I feel like there is a better way I cannot find through Google / Drupal API etc. Something like:

$term = taxonomy_by_description_load('my_vocabulary', 'my_term_description');

Thanks everyone.

0

1 Answer 1

0

Using the EntityFieldQuery (this is untested)

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->entityCondition('bundle', array('my_vocabulary'))
    ->propertyCondition('description', 'my_term_description');
  $result = $query->execute();
  $tids = array_keys($result['taxonomy_term']);

  return $tids;

More information https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-use-entityfieldquery-for-drupal-7

1
  • 1
    Thanks! Unfortunately I don't have enough rep points to vote for an answer to my own question :(
    – 100pic
    Commented Feb 15, 2017 at 4:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.