How to delete nodes in bulk programmatically from a drupal site?

March 05, 2010 - 02:19

What do you do when you want to delete multiple nodes from a drupal site? You go to admin » content and then delete nodes one by one? No. You go to PhpMyadmin and delete the nodes from the node table?. Absolutely not (don't even think about it). There are a few solutions. There is the Views Bulk Operations module. But there is an easy hack to do this or for that matter bulk node operations.

Suppose you wish to delete all nodes by a particular user say user 1000. Create a php file with whatever name you wish to give it and put it in the root folder. Let us call it whatever.php. Copy the following contents into the file

include_once './includes/';
include_once './includes/';
$i = 0;
$sql = db_query("SELECT n.nid, n.title FROM {node} n WHERE n.uid = 1000");
while ($n = db_fetch_object($sql) && user_access('administer nodes')) {
  $nid = $n->nid;
  $title = $n->title;
  print 'Deleted '. $i . ':' . $nid . ':' . $title . '<br />';
print 'Deleted '. $i .' nodes.';

If the number of nodes are few (a few hundreds) then running this script from the web should do the trick. If you wish to do more complex programmatic changes on nodes in bulk then you should make the changes accordingly in the above file and then invoke the script using from the command line. If that is the case you could take out the user_access check from above and alternatively introduce the following piece of code to ensure that the file is being run from the command line.

if(!empty($_SERVER['REQUEST_METHOD'])) {
  print 'This script can be executed only from the command line';

Get Drupal updates straight to your inbox

To prevent automated spam submissions leave this field empty.

Post your comments / questions

nice one...i just joined this it worth?

I appreciate your help, I was trying to do this in the .htaccess the whole time but I dint realize it could be done in the php script itself. Thanks for your valuable post.

Thanks, You save my time!