Deleting a Whole Taxonomy from the Database
Published on — No Comments

To carry out such a task, there is no utility function made up on purpose in WordPress. After all, deleting all the data associated to a taxonomy isn't a common task, or at least not something you routinely do. Me, for example, I ran into the problem while writing the uninstall.php
script for SiteTree Pro 4.0 — a file loaded when not all the WordPress functions are available, either. But even considering a more generic context, the most streamlined solution that can be adopted is to use three custom queries:
global $wpdb;
$taxonomy_name = 'the_taxonomy_to_delete';
# Deletes all the terms associated to the taxonomy.
#
# The inner query collects from the 'term_taxonomy' table
# all the ids of the terms to delete.
$wpdb->query(
"DELETE FROM {$wpdb->terms} AS t
WHERE t.term_id IN (
SELECT tt.term_id FROM {$wpdb->term_taxonomy} AS tt
WHERE tt.taxonomy = '{$taxonomy_name}'
)"
);
# Deletes the information used by WordPress to link each post
# to their terms.
#
# Here too a nested query is needed, and the 'term_taxonomy' table
# is yet again the source of the data passed to the outer query.
# But in this case to be collected by the inner query are the ids of
# the Relationships to delete.
$wpdb->query(
"DELETE FROM {$wpdb->term_relationships} AS tr
WHERE tr.term_taxonomy_id IN (
SELECT tt.term_taxonomy_id FROM {$wpdb->term_taxonomy} AS tt
WHERE tt.taxonomy = '{$taxonomy_name}'
)"
);
# Deletes the base information about the taxonomy.
$wpdb->query(
"DELETE FROM {$wpdb->term_taxonomy}
WHERE taxonomy = '{$taxonomy_name}'"
);
The database must be queried in three distinct times not only because three are the tables from where to delete data, but mainly because two of them, terms
and term_relationships
, depend on the third, term_taxonomy
.