Blog IT

Here are the two methods to delete the nodes in Drupal 8 programmatically.

1) Using NID

use Drupal\node\Entity\Node;

$nid = 123;
$node = Node::load($nid);
// or
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

// Check if node exists with the given nid.
if ($node) {
  $node->delete();
}

2) Using some criteria (for example, older than 90 days)

$nodes = \Drupal::entityQuery("node")
  ->condition('created', strtotime('-90 days'), '>=')
  ->execute();

$storage_handler = \Drupal::entityTypeManager()->getStorage("node");

if (!empty($nodes)) {
  foreach ($nodes as $key => $value) {
    $node = $storage_handler->load($value);
    $node->delete($node);    
  }
}