WordPress Delete Unused Post Tags By SQL Command
Posted by in Tips And Tricks June 29, 2011 5 Comments

Few days ago, I deleted a lot of dump posts from one of my WordPress site. After that, I recognized there were ton of unused tags existed in the database. It’s wasting the server resources and slow down my site by retrieving/looping unnecessary records.

Therefore, I decided to clean up all unused tags to free up all related tables and increase the performance as well as page loading time.

SQL Commands to delete/remove all unused post tags in WordPress

You can use PhpMyAdmin or a particular SQL client to run these commands below. Again, please backup your database first and make sure you understand what are you doing.

DELETE FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE COUNT = 0 );
DELETE FROM wp_term_taxonomy WHERE term_id NOT IN (SELECT term_id FROM wp_terms);
DELETE FROM wp_term_relationships WHERE term_taxonomy_id NOT IN (SELECT term_taxonomy_id FROM wp_term_taxonomy);

I worked on my side and significant reduce the database site. Remember to replace ‘wp_’ with your table_prefix.

After deleted all unused tags and its relationship, you should optimize those tables to reclaim the unused space and to defragment the data file. It’s very useful when you have deleted a large part of a table and definitely improve performance.

OPTIMIZE TABLE `wp_terms` , `wp_term_taxonomy` , `wp_term_relationships`;

Good luck :)

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • http://www.google.com/ Trevion

    Well done aitrcle that. I’ll make sure to use it wisely.

  • http://suckup.de/ Voku

    thx for sharing this SQL-Code :)

  • Carol

    How would you change the command to delete a tag that has less than 3 posts attached to it? 

    • http://4rapiddev.com/ Hoan Huynh

      Hi Carol,

      Simply try to adjust the first SQL statement as below:

      ——————————

      DELETE FROM wp_terms WHERE term_id IN (SELECT term_id FROM wp_term_taxonomy WHERE COUNT < 3 );
      ——————————

      with '3' is the post limit.Please back up your database before trying :)

      Hope this helps.

      H2.

  • T. J. Brumfield

    I inherited a site from someone else with a lot of old content. Some of the old writers came over to the new site, and others didn’t. I removed old posts via SQL for the authors who didn’t come over to the new site, which proved to be a bit of a mistake. Since I didn’t delete the posts manually through WordPress, it didn’t update the tag count. Now I have 3,000 tags, many of which say they have been used when they aren’t being used by actual content on my site.

    Is there a way via SQL I can force WordPress to recalculate actual tag count?