Last active
August 29, 2015 14:04
-
-
Save orionrush/2de5fc246e611e5861a3 to your computer and use it in GitHub Desktop.
Two ways to delete WP taxonomies and their terms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
register_uninstall_hook( __FILE__, 'do_delete_terms_wpdb' ); | |
/** | |
* Delete database entries of terms and taxonomies using wordpress SQL api $wpdb | |
* | |
* @global $wpdb | |
* @wp-hook register_uninstall_hook | |
* @author Travis Smith | |
* http://wpsmith.net/2014/wp/plugin-uninstall-delete-terms-taxonomies-wordpress-database/ | |
*/ | |
function do_delete_terms_wpdb() | |
{ | |
global $wpdb; | |
$taxonomies = array('term_1', 'term_2'); | |
foreach ($taxonomies as $taxonomy) { | |
if (taxonomy_exists($taxonomy)) { | |
// Prepare & execute 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')); | |
} | |
} | |
} | |
register_uninstall_hook(__FILE__, 'do_delete_terms'); | |
/** | |
* Delete taxonomies and their terms using | |
* | |
* @uses get_terms | |
* @uses wp_delete_term | |
* @wp-hook register_uninstall_hook | |
* @author orionrush | |
*/ | |
function do_delete_terms() | |
{ | |
$taxonomies = array('term_1', 'term_2'); | |
foreach ($taxonomies as $taxonomy) { | |
if (taxonomy_exists($taxonomy)) { | |
$terms = get_terms($taxonomy, array('fields' => 'ids', 'hide_empty' => false)); | |
foreach ($terms as $term) { | |
wp_delete_term($term, $taxonomy); // delete each term | |
} | |
register_taxonomy($taxonomy, array()); // delete the taxonomy? | |
// unset( $wp_taxonomies[$taxonomy]); // will this delete the taxonomy? | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment