Drupal - How to iterate over all the nodes from a content type

Drupal core provides a class called EntityFieldQuery(). There is also a handy document page for using it, that has lots of examples. In its simplest form:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'page')
  ->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    // do something awesome
  }
}

This will load all published nodes of type "page". You periodically need to adjust this to

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'page')
  ->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);

 foreach ($nids as $nid) {
    $node = node_load($nid, NULL, TRUE);
    // do something awesome
  }
}

to avoid loading too much at once, which can cause memory issues.


You can query that information directly through node_load_multiple()

$nodes = node_load_multiple(array(), array('type' => 'my_type'));

You can add as many property conditions to the $conditions array (second argument) as you like, so status, created, etc are fair game too.

$conditions is technically deprecated (I imagine in favour of EntityFieldQuery) but the chances of that functionality ever being removed from Drupal 7 are basically none. It would break too much.

Tags:

Nodes

7