Drupal 7 – Batch update nodes by cron

The following piece of code will update a field of a specific content type by SQL and it is written in a custom module with hook_cron(). Since it updates the database table directly so you have to use it with extreme caution.

function <MODULE>_cron() {
  // Get the list of node ids
  $sql = "SELECT nid FROM {node} WHERE type = :type";
  $result = db_query($sql, array(':type' => '<TYPE>'));
  $nids = array();
  foreach ($result as $row) {
    $nids[] = $row->nid;
  }

  // Update the table directly
  db_update('<FIELD TABLE NAME>')
    ->fields(array('<FIELD NAME>' => '<NEW VALUE>'))
    ->condition('entity_id', $nids)
    ->execute();
  
  // Clear the cache
  drupal_flush_all_caches();
}

 

Done =)

About these ads

One thought on “Drupal 7 – Batch update nodes by cron”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s