Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Simple loop to update nodes

Parent Feed: 

For some reason I find myself rewriting this little bit of code every time I need to update a bunch of nodes on a site. Going to post it here to save myself some time. Be aware that this might time out if you've got a large number of nodes, designed for up to a couple hundred nodes:

<?php
// TODO: Set your basic criteria here:
$result = db_query("SELECT n.nid FROM {node} n WHERE n.type = '%s'", array('task'));
while (
$row = db_fetch_array($result)) {
 
$node = node_load($row);
  if (
$node->nid) {
   
$node->date = $node->created;    // TODO: Test and set your own value here:
   
if (empty($node->field_task_status[0]['value'])) {
     
$node->field_task_status[0]['value'] = 'active';
     
$node = node_submit($node);
     
node_save($node);
     
drupal_set_message(t('Updated <a href="http://drewish.com/content/2009/08/simple_loop_to_update_nodes/!url">%title</a>.', array('!url' => url('node/'. $node->nid), '%title' => $node->title)));
    }
  }
}
?>
Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web