Questions? Feedback? powered by Olark live chat software How to delete nodes in bulk programmatically from a drupal site? | Zyxware Technologies

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

<?php
include_once './includes/bootstrap.inc';
include_once './includes/common.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$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;
  node_delete($n->nid);
  print 'Deleted '. $i . ':' . $nid . ':' . $title . '<br />';
  $i++;
}
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 drupal.sh 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';
  exit;
}

Post your comments / questions

nice one...i just joined this site...is 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!

You may also like