IT.COM

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

Spaceship Spaceship
Watch
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:
<?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
  $entities = $nodeQuery->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'food_menu_item') //change 'food_menu_item' to target content_type
    ->propertyCondition('status', 1) //get only nodes that are 'published'
    ->fieldCondition('field_food_menu', 'tid', 2) //replace field_food_menu with field_TAXONOMY_NAME and 2 with taxonomy ID (or use this code in a loop for many terms)
    ->execute();

  //$entities will now have an array with the node IDs that match your criteria
  // you can now use something like node_load() to get more data about these nodes
?>

------------Signature------------
http://www.famesbond.com : famesbond.com, stundate.com, asksubtitles.com, everydoctor.info, kohlcall.com - and many other premium domains available for sale! :wave:
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back