25 Mar.2020

Drupal 10: Remove all nodes from the site programmatically

drupal entities

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 are the examples.

$ids = \Drupal::entityQuery('node')->accessCheck(FALSE)->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();
  }
}
// Removes all nodes for Alert content type.
$ids = \Drupal::entityQuery('node')->condition('type', 'social_post')->accessCheck(FALSE)->execute();
$storageHandler = \Drupal::entityTypeManager()->getStorage('node');
$entities = $storageHandler->loadMultiple($ids);
foreach ($entities as $entity) {
     $entity->delete();
}

Ruslan Piskarov

Ukraine
PHP/WEB Developer / Drupal Expert. More than 11 years of experience delivering Drupal based General Purpose solutions for different sectors such as Job Boards, Product Portfolios, Geo Coding, Real Estate solutions, E-Commerce, Classifieds, Corporate and online Magazines/Newspapers.

Versions