Delete Orphaned terms from vocabulary (Drupal)

We have been managing several websites powered by Drupal. Over the years we have found that we have several terms that do not have any nodes associated with them, thus rendering empty pages for those keyword.

Here is a small piece code to delete those terms. This can be added to cron to make sure terms are cleaned regularly.


$vid = 3; // Vocabulary ID
$terms = taxonomy_get_children($tid = 0, $vid);
foreach ($terms as $term) {
if (taxonomy_term_count_nodes($term->tid) == 0) {
// See if any nodes use the terms. If none, delete the terms.
taxonomy_del_term($term->tid);
echo "Deleting...".$term->name;
}
}

This code has been tested with Drupal 6.x, but should work for 7.x