I want to recover some info from a field of all the nodes of a specific content type.
I know how to do it using a db_query
and getting all the node ID then iterate over them.
What I would like to know is if there's is another way around this using drupal functions.
2 Answers
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.
-
3
-
I will accept this answer since it's exactly what I was looking for, but will use @MPD solution because it will also work with Drupal 8 :)– drcelusJun 28, 2013 at 13:19
-
@drcelus Yes MPD's method is definitely the best way to go, I probably should have mentioned that -
EntityFieldQuery
all the way :) I put this is in more for posterity than anything else– Clive ♦Jun 28, 2013 at 13:22 -
1
entity_load_multiple
exists in D8. You can't load by properties though.– user49Jul 2, 2013 at 20:10 -
Thanks for the clarification. I did mean that $conditions is gone from D8.– mpdonadio ♦Jul 2, 2013 at 20:29
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.