Many developers do not consider what they should do when a person deactivates a plugin (like flush_rewrite_rules()), much less what to do with the data the plugin created, much of which is useless. In my opinion, this is partly because creating an extra uninstall.php
file is a bit problematic to test over and over.
So, in this snippet, here is how you can delete ALL the terms and the associated taxonomy when a plugin is deleted by a user. First create a file called uninstall.php
which appears at the root of the plugin. Then add this code:
<?php | |
/** Delete All the Taxonomies */ | |
foreach ( array( 'my_first_custom_tax', 'my_second_custom_tax', 'my_third_custom_tax', ) as $taxonomy ) { | |
// Prepare & excecute SQL, Delete Terms | |
$wpdb->get_results( $wpdb->prepare( "DELETE t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('%s')", $taxonomy ) ); | |
// Delete Taxonomy | |
$wpdb->delete( $wpdb->term_taxonomy, array( 'taxonomy' => $taxonomy ), array( '%s' ) ); | |
} |
Sometimes, however, you may need to do something else between the code. For example, you may have custom term meta within the options table that would need to be deleted as well.
<?php | |
/** Delete All the Taxonomies */ | |
foreach ( array( 'my_first_custom_tax', 'my_second_custom_tax', 'my_third_custom_tax', ) as $taxonomy ) { | |
// Prepare & excecute SQL | |
$terms = $wpdb->get_results( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('%s') ORDER BY t.name ASC", $taxonomy ) ); | |
// Delete Terms | |
if ( $terms ) { | |
foreach ( $terms as $term ) { | |
$wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $term->term_taxonomy_id ) ); | |
$wpdb->delete( $wpdb->terms, array( 'term_id' => $term->term_id ) ); | |
delete_option( 'prefix_' . $taxonomy->slug . '_option_name' ); | |
} | |
} | |
// Delete Taxonomy | |
$wpdb->delete( $wpdb->term_taxonomy, array( 'taxonomy' => $taxonomy ), array( '%s' ) ); | |
} |
Leave a Reply