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)
  // Clear the cache


Done =)

3 thoughts on “Drupal 7 – Batch update nodes by cron”

  1. Hello,

    thanks for ths solution.
    How can I set the fields value ( fields(array(” => ”)) ) on “today” when it’s a date field?

    Best regards


    1. That depends on the format you have set on your datetime field. Here is an example:

      $date = new DateTime() // Get current datetime
      // For datetime
      $node->field_datetest[$node->language][0]['value'] = $date->format('Y-m-d H:i:s'); // 2015-01-16 09:21:32
      // For date
      $node->field_datetest[$node->language][0]['value'] = $date->format('Y-m-d\TH:i:s'); // 2015-01-16T09:21:32
      // For datestamp
      $node->field_datetest[$node->language][0]['value'] = strtotime($date->format('Y-m-d H:i:s'));


      I haven’t tried that, to play safe, please check the corresponsding value stored in the database and make a backup whenever it is needed.

      Reference: Programmatically set date fields in Drupal 7: Date, Date (ISO Format) and Date (Unix Timestamp)


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