I am writing my plugin’s uninstall.php file and would like it to delete any terms that were created in the plugin’s custom taxonomy.
In the plugin’s uninstall.php file I am using this:
// Delete all custom terms for this taxonomy
$terms = get_terms('custom_taxonomy');
foreach ($terms as $term) {
wp_delete_term( $term->ID, 'custom_taxonomy' );
}
The problem seems to be that the custom taxonomy isn’t registered at this point, so get_terms returns an error for “invalid taxonomy”, thus I can’t delete the custom terms in this manner, which seems the most straightforward way to do so.
If the custom taxonomy isn’t registered when uninstall.php is called, how can I have it so that my plugin is able to clean up it’s custom data?
Any help is greatly appreciated.
Thanks.
Using the uninstall hook would be legitimate if it worked, but it dumps the same error as the uninstall file. It would have more chances of working as it loads the main plugin file to perform the uninstall function, but if the taxonomy is not registered anymore (and it is not, as we need to deactivate before uninstalling), WP cannot use
get_terms
.Adapting the following function from this Stack Overflow answer should do the work:
Based on input from brasofilo, here is what I ended up doing:
Call your cleaning function when uninstalling your plugin through
register_uninstall_hook
I know this is 10 years old but as it came up on Google, I found , after some experiments a simpler solution.
Simply re-register the taxonomy in your uninstall code e.g.