For my job site, jobs are tagged from terms of Tags vocabulary where new ones can be added. Sooner jobs expire and new arrive.

That has resulted in bloated taxonomy vocabulary with 2400 terms (or 2400 pages). I guess many remain empty for long periods.

Many tag pages simply show no classified content available which has attracted Google's Panda penalty.

What I want is removing those tags not used for any node, and automatically deleted those that have not been used in the past 3 months or so get.

Is there any simple way for doing this?

1 Answer 1


I have a similar script that I use, but I run it as a drush scr. You can adapt it for your needs, perhaps to do this in a hook_cron():

$tags = taxonomy_vocabulary_machine_name_load('tags');

$tids = db_query('
  FROM {taxonomy_term_data} t
  LEFT JOIN {taxonomy_index} i ON i.tid = t.tid
  WHERE t.vid = :vid
    AND i.tid IS NULL
', array(':vid' => $tags->vid))->fetchCol();

if (!empty($tids)) {
  foreach ($tids as $tid) {

  watchdog('foo', 'deleted @count orphaned tags', array(
    '@count' => count($tids),

This exact version is untested and a hand-edit from a very specific use-case I have. Take backups and use at your own risk!

The only problem is that {taxonomy_term_data} doesn't have a created column, so this will immediately delete orphaned terms. It also doesn't take into term hierarchy, or tags being on entities other than nodes.

  • Thanks. Will it work for Drupal 8 too?
    – AgA
    Mar 20, 2014 at 11:34
  • @AgA No it won't. functions like taxonomy_term_delete are not avail. in D8. You will need to workaround with Entity API I think.
    – AKS
    Mar 20, 2014 at 11:57
  • Worked perfectly, thankyou. If you have the devel module enabled, you can execute it directly at 'devel/php'
    – 2pha
    Dec 21, 2014 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.