SQL clean wp term as tags, product tags

Cleaning the terms in wordpress database, particularly removing unused or orphaned entries, involves a series of SQL queries to ensure data integrity across related tables. It is crucial to back up your database before running any of these queries.
The primary goal is often to remove terms that are no longer associated with any posts or content, indicated by a count of 0 in wp_term_taxonomy.
Here’s a set of SQL queries to clean wp_term_taxonomy and related tables:
  • Delete terms with a count of 0: This removes the actual terms from wp_terms that are not linked to any content.
Code

DELETE FROM wp_terms WHERE term_id IN ( SELECT term_id FROM wp_term_taxonomy WHERE count = 0 );

  • Delete corresponding entries in wp_term_taxonomy: After removing the terms, remove the corresponding taxonomy entries.
Code

DELETE FROM wp_term_taxonomy WHERE term_id NOT IN ( SELECT term_id FROM wp_terms );

  • Delete orphaned entries in wp_term_relationships: This ensures that no relationships point to non-existent term_taxonomy_ids.
Code

DELETE FROM wp_term_relationships WHERE term_taxonomy_id NOT IN ( SELECT term_taxonomy_id FROM wp_term_taxonomy );

Important Considerations:
  • Custom Taxonomies:
    These queries target general term_id and count values. If you have custom taxonomies and want to clean only specific ones (e.g., post_tag), you can add a WHERE taxonomy = 'your_taxonomy_slug' clause to the wp_term_taxonomy subqueries.
  • Orphaned Posts/Attachments:
    If you are cleaning up after deleting posts or attachments, you might also need to clean wp_postmeta and wp_term_relationships entries where object_id no longer corresponds to an existing wp_posts.ID.
  • Performance:
    For very large databases, consider running these queries during off-peak hours or in smaller batches if possible.
  • Testing:
    Always test these queries on a staging or development environment before applying them to a live production database.
0378.59.00.99