Drupal 8: Remove all nodes from the site programmatically

25 Mar.2020
nodes

Sometimes we need to completely remove all nodes, for example, when you copy a site for another project.

You can use custom code in your custom module or install devel_php and run with the admin interface on /devel/php.

Below the examples.

$ids = \Drupal::entityQuery('node')->execute();
$storageHandler = \Drupal::entityTypeManager()->getStorage('node');
$entities = $storageHandler->loadMultiple($ids);
foreach ($entities as $entity) {
  // Remove media created by an anonymous user only.
  if ($entity->getOwnerId() == 0) {
     $entity->delete();
  }
}