Delete nodes programmatically

Fast Track to Drupal 8 Coding – Back to intro
Previous lesson - Create nodes programmatically
Next lesson – Unpublish nodes programmatically

Lesson Goal

Delete all nodes with certain criteria (for example, older than 30 days) during a cron run.

Implementation Method

Drupal Version Method
Drupal 7 Use hook_cron with node_delete_multiple
Drupal 8 Use hook_cron with EntityStorageInterface::delete

Drupal 7 method

  1. Add the following in lotus.module file:

      function lotus_cron() {
      $results = db_select('node', 'n')
                  ->fields('n', array('nid'))
                  ->condition('created', strtotime('-30 days'), '<=')
                  ->execute();
      foreach ($results as $result) {
        $nids[] = $result->nid;
      }
      if (!empty($nids)) {
        node_delete_multiple($nids);
      }
    }
    
  2. Run cron.

Drupal 8 method

  1. Add the following in lotus.module file:

    function lotus_cron() {
      $result = \Drupal::entityQuery("node")
        ->condition('created', strtotime('-30 days'), '<=')
        ->execute();
    
      $storage_handler = \Drupal::entityTypeManager()->getStorage("node");
      $entities = $storage_handler->loadMultiple($result);
      $storage_handler->delete($entities);
    }
    
  2. Run cron.

Contact supportStill need assistance? Contact Acquia Support

Acquia: Think Ahead

53 State Street, 10th Floor
Boston, MA 02109
United States
Phone: 888-922-7842

Map: Google Maps
View other locations