Extra Block Types (EBT) - New Layout Builder experience❗

Extra Block Types (EBT) - styled, customizable block types: Slideshows, Tabs, Cards, Accordions and many others. Built-in settings for background, DOM Box, javascript plugins. Experience the future of layout building today.

Demo EBT modules Download EBT modules

❗Extra Paragraph Types (EPT) - New Paragraphs experience

Extra Paragraph Types (EPT) - analogical paragraph based set of modules.

Demo EPT modules Download EPT modules

Scroll

Drupal 8 delete node programmatically

Drupal 8 delete node programmatically
, by
Drupal 8 delete node programmatically
1 answer
votes: 1367
Answer

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);    
  }
}