Community Documentation

Querying to get a list of taxonomy terms or nodes using EntityFieldQuery

Last updated February 21, 2013. Created by adityamenon on April 6, 2012.
Edited by Gold. Log in to edit this page.

This belongs inside your module code.

You can get a collection of nodes matching particular parameters by using EntityFieldQuery, instead of writing an SQL statement. I had a hard time getting all the syntax together, so here are a couple of simple samples:

<?php
 
// fetch the taxonomy terms inside a particular vocabulary
 
$taxonomyQuery = new EntityFieldQuery();
 
$taxonomyTerms = $taxonomyQuery->entityCondition('entity_type', 'taxonomy_term')
    ->
propertyCondition('vid', 2) //change 2 to any vocabulary ID
   
->propertyOrderBy('weight')
    ->
execute();
  foreach(
$taxonomyTerms['taxonomy_term'] as $term) {
   
$relevantTerms[] = $term->tid;
  }

 
// $relevantTerms will now have the terms of your target vocabulary
?>

<?php
 
//get a list of nodes that match your criteria
 
$nodeQuery = new EntityFieldQuery();
 
$entities = $nodeQuery->entityCondition('entity_type', 'node')
   
// change 'food_menu_item' to target content_type
   
->entityCondition('bundle', 'food_menu_item')
   
// get only nodes that are 'published'
   
->propertyCondition('status', 1)
   
// replace field_food_menu with field_TAXONOMY_NAME
    // replace 2 with the taxonomy ID (tid) you're wanting
   
->fieldCondition('field_food_menu', 'tid', 2);

 
// If multiple tids are required use this code in a loop with
  // one tid per fieldCondition()
 
$restriction_tids = array(13,15);
  foreach (
$restriction_tids as $r_tid){
   
$entities->fieldCondition('field_food_restrictions', 'tid', $r_tid);
  }

 
// If you want to check for at least one of a list of tids replace 2
  // with an array.  e.g. array(2,4,5)
 
$which_menu_tids = array(23,24);
 
$entities->fieldCondition('field_which_menu', 'tid', $which_menu_tids, 'IN');

 
$entities->execute();

 
// $entities should now have an array with the node IDs that match
  // your criteria. In this case :
  // field_food_menu term ID 2
  // AND field_food_restrictions term ID 13
  // AND field_food_restrictions term ID 15
  // AND field_which_menu term ID 24 OR 24

  // you can now use something like node_load() to get more data about these nodes
 
foreach ($entities as $rows) {
    foreach (
$rows as $row) {
     
$nodes[] = node_load($row->entity_id);
    }
  }
?>
nobody click here