[Drupal] Deleting node content of a certain type in bulk

On occasions you may need to bulk delete all nodes of a certain type.

The following code requires 2 variables, the amount of rows to delete each time and the content type.

<?php$amount = 100;
$type = 'node_type';
$result = db_query("SELECT nid FROM {node} WHERE type = '%s' LIMIT %d", $type, $amount);
if (db_num_rows($result) && user_access('administer nodes')) {
  $n = 0;
  while ($data = db_fetch_object($result)) {
    set_time_limit(5);
    node_delete($data->nid);
    $n++;
  }
  if ($n == $amount) {
    drupal_goto($_GET['q']);
  }
}else {
  drupal_set_message(t('No entries found for node type @type, or you do not have permission to modify nodes.', array('@type' => $type)));
}?>

This will go through all the nodes of the type you define and delete the node. Once finished doing the batch, the page is then redirected back to the same page to delete another batch.

This can be placed in a node with an Input format of PHP code or through a module.

<?phpfunction modulename_menu($may_cache) {
  $items = array();
  if (!$may_cache) {
    $items[] = array(
      'path' => 'this/is/the/path',
      'callback' => 'modulename_delete',
      'access' => user_access('administer nodes'),
      'title' => t('Delete Nodes'),
    );
  }
  return $items;
}?>

Then wrap the above deletion code into a function such as:

<?phpfunction modulename_delete($type = 'node_type', $limit = 100) { }?>

Then you can navigate to the path in the hook_menu function and start the batch deletion. To delete other types of nodes, add the content type to the end of the url. For events it would be:

http://www.domain.com/this/is/the/path/event

Depending on what modules you have enabled, this can take a long time as the node_delete function calls a module_invoke function for any module to interact with it. If you have a lot of modules this will take a long time.

Alternatively you can download and install the Delete all module which serves the same function.

Comments

Is there any way I could do the buld deletion without tweaking SQL queries?

What?