Is there a function in Drupal 7 to pull all instances of a specific content type to store in an array? Ex: Say I have a content type called "us_states" and I want to pull each instance of that type (with it's saved data so the title, description, and the custom content I created) and store them into an array. How should I go about doing that?
2 Answers
Two options: node_load_multiple()
function (deprecated) or EntityFieldQuery
Class (preferred).
Example
node_load_multiple()
:$nodes = node_load_multiple(array(), array('type' => 'us_states'));
The second argument (
$conditions
) is marked as deprecated; and you can see that in the Drupal 8 documentation for the same function, it has been removed. I only included this example because I'm sure someone else would have pointed it out had I not and the fact that you specifically asked for a function.Example
EntityFieldQuery
(Use this):$query = new EntityFieldQuery(); $query->entityCondition('entity_type', 'node') ->entityCondition('bundle', 'us_states'); $nodes = $query->execute();
In both examples, $nodes
will be an array containing all nodes of the content type 'us_states'. (Note that the nodes within the array will be objects per usual.)
If you really need to use a function (that won't be deprecated in Drupal 8), you can pass an array of Node IDs as the first param to node_load_multiple()
that contains the Node IDs of all of the 'us_states'.
-
I'm pretty sure EntityFieldQuery doesn't return full node objects, you need to load them as it only returns nid, vid and some other field I can't remember (I think it was status?). But for anyone looking at this answer, there's a good guide on how to use EntityFieldQuer here: How to use EntityFieldQuery– BeebeeCommented Aug 21, 2015 at 9:32
-
Beebee is right. To get the whole node objects using EntityFieldQuery, you have to get the NIDs from its result set into an array and pass it as argument to node_load_multiple(). Commented Jan 29, 2016 at 19:11
You need to get an array of node ids from the database first. Simple db_select
query will do the job.
$nids = db_select('node')
->fields('node', array('nid'))
->condition('node.type', 'us_states')
->execute()
->fetchCol();
And then pass that array to node_load_multiple($nids)
.
You should be OK memory-wise when loading 50 nodes all at once. But you should be cautious when the total number of nodes is significant (more than 100 I'd say).