Deleting nodes tagged with a taxonomy term

Occasionally, we find ourselves with a area of the website that we no longer use and can safetly delete. Normally, it’s a very small area of the site, and one of our content administrators will delete the nodes, then I’ll remove the files and the taxonomy term associated with the nodes (we use Drupal’s taxonomy module to regulate permission and to generate URLs).

But today we had the opportunity to delete several hundred nodes all at once, under about a dozen taxonomy terms. Time to script it.

After backing up your database, you can run this by specifying the $termid that you want to delete, then calling drush scr ~/path/to/script/delete_term_and_nodes.php.

<?php
//Enter the taxonomy term ID you want to delete
$termid = -1;
$allterms = taxonomy_get_children($termid);
$allterms[] = $termid;
echo "Deleting $termid and its children\n";
echo "Deleting " . count($allterms) . " terms\n";
foreach($allterms as $term) {
$term = taxonomy_term_load($term);
$nodes = taxonomy_select_nodes($term->tid, false);
echo $term->name . " has " . count($nodes) . " children to delete\n";
$successful_delete = true;
try{
node_delete_multiple($nodes);
}
catch(Exception $e) {
echo "Error deleting nodes in " . $term->name . ", check manually\n";
$successful_delete = false;
}
if($successful_delete) {
taxonomy_term_delete($term->tid);
echo "Deleted taxonomy term " . $term->name . "\n";
}
}
taxonomy_term_delete($termid);
echo "Parent term deleted. All set!\n";
?>
©2022 Kyle Schmidt some rights reserved