Delete nodes programatically

Tutorial Goal

Lesson Goal:

Implementation Method

D7

D8

hook_cron + node_delete_multiple

hook_cron + EntityStorageInterface::delete

 

D7 Code

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

D8 Code

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

Gist Link

https://gist.github.com/gargsuchi/e2f492b0586900e152f0d86c951f398d

Contact supportStill need assistance? Contact Acquia Support