How to delete nodes by type and clean up sequences

Last modified: January 5, 2009 - 13:03

When developing on a new Drupal site you might need to create lots of test nodes. The developer module is of a great help for this, as well as deleting previous content. However, it deletes previous content only when creating new test content and it doesn't update sequences in any case, so you might end up having new nodes created with a very high nid, even if you only have few nodes.

To solve this I use this snippet, borrowed from the developer module, plus some new queries to update the sequences for nodes. You just need to replace the xxxxxx strings with the node types you want to delete.

<?php

$node_types
= array(
 
'xxxxxx', //update this string with the type of node you want to delete
 
'xxxxxx', //update this string with the type of node you want to delete and add any more lines you might need
);

$sql = 'SELECT nid FROM {node} WHERE type IN ('. implode(', ', array_fill(0, count($node_types), "'%s'")). ')';
   
$result = db_query($sql, $node_types);
    while (
$row = db_fetch_object($result)) {
     
node_delete($row->nid);
    }

db_query("UPDATE sequences SET id = (SELECT MAX(nid) FROM {node}) WHERE name = '{node}_nid'");
db_query("UPDATE sequences SET id = (SELECT MAX(vid) FROM {node_revisions}) WHERE name = '{node}_revisions_vid'");

?>

 
 

Drupal is a registered trademark of Dries Buytaert.