Update Field Value for All Nodes
I recently added a “Show in Listing” boolean on/off checkbox field to a content type (default value is to be “checked”). There were 133 nodes when I created that field. I needed to update all of those nodes to be “checked”.
Here’s how I updated all of them using entity_metadata_wrapper(). It’s much quicker than any alternative I could think of (feeds, rules, etc.).
1 2 3 4 5 6 7 8 9 10 11 |
$nids = db_query('SELECT nid FROM {node} WHERE type = :type', array(':type' => 'blogpost'))->fetchCol(); foreach ($nids as $nid) { $node = node_load($nid); if ($node) { $wrapper = entity_metadata_wrapper('node', $node); if (isset($wrapper->field_islisted)) { $wrapper->field_islisted->set(1); $wrapper->save(); } } } |
In this particular case I’m targeting a single content type. I could’ve used a similar query and some slight modifications to set the value on any node whose bundle (content type) supports that field_islisted field.
Lastly, if you have a lot of nodes, you might consider using node_load_multiple() instead of node_load() .