Skip to content

Instantly share code, notes, and snippets.

@wpsmith
Last active April 21, 2023 13:15
Show Gist options
  • Select an option

  • Save wpsmith/9285391 to your computer and use it in GitHub Desktop.

Select an option

Save wpsmith/9285391 to your computer and use it in GitHub Desktop.
PHP: How to delete terms and taxonomies in uninstall.php
<?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' ) );
}
<?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' ) );
}
@wpsmith
Copy link
Copy Markdown
Author

wpsmith commented Mar 1, 2014

@aolin480
Copy link
Copy Markdown

I would take it one step further and add the following to remove term relationships? Not too sure if there was a methodology you had to leave those out.

After:
$wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $term->term_taxonomy_id ) );

Add:
$wpdb->delete( $wpdb->term_relationships, array( 'term_taxonomy_id' => $term->term_taxonomy_id ) );

It would look like this:

foreach ( $terms as $term ) {
    $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $term->term_taxonomy_id ) );
    $wpdb->delete( $wpdb->term_relationships, 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' );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment