Drupal - How to delete all nodes of a given content type?

There is a module for that (TM).

See Bulk Delete.

That will use the Batch API to delete the nodes to avoid timeout or memory issues when deleting thousands of nodes with a single call to node_delete_multiple().

Bulk Delete is an abandoned module. See for alternatives:

  • Views Bulk Operations

  • Delete All


Looking at the Devel Generate module for inspiration, here is its "content kill" function devel_generate_content_kill:

function devel_generate_content_kill($values) {
  $results = db_select('node', 'n')
              ->fields('n', array('nid'))
              ->condition('type', $values['node_types'], 'IN')
              ->execute();
  foreach ($results as $result) {
    $nids[] = $result->nid;
  }

  if (!empty($nids)) {
    node_delete_multiple($nids);
    drupal_set_message(t('Deleted %count nodes.', array('%count' => count($nids))));
  }
}

So I would try either using Devel Generate to delete all nodes but create no new ones, or use example.com/devel/php to call devel_generate_content_kill(array('node_types' => array('my_node_type'))); directly.


In Drupal 8 one way is use the entityQuery() method with the EntityStorageInterface::delete() method:

$result = \Drupal::entityQuery("node")
    ->condition("type", "YOUR_CONTENT_TYPE_NAME")
    // If the update is being executed via drush entityQuery will only
    // return the content uid 0 have access to. To return all set
    // accessCheck to false since it defaults to TRUE. 
    ->accessCheck(FALSE)
    ->execute();

$storage_handler = \Drupal::entityTypeManager()->getStorage("node");
$entities = $storage_handler->loadMultiple($result);
$storage_handler->delete($entities);

If you need to apply other filters/conditions you can check the QueryInterface interface page

EDIT (Other way, thanks to @4k4):

$storage_handler = \Drupal::entityTypeManager()->getStorage("node");
$entities = $storage_handler->loadByProperties(["type" => "YOUR_CONTENT_TYPE_NAME"]);
$storage_handler->delete($entities);

If you want to test the code you can use:

drush php-eval '$storage_handler = \Drupal::entityTypeManager()->getStorage("node"); $entities = $storage_handler->loadByProperties(["type" => "article"]); $storage_handler->delete($entities);'

This will delete all your articles.

Tags:

Nodes