Last active
December 28, 2022 22:17
-
-
Save sabrina-zeidan/d812d794998f1a1c56029d54df435caa to your computer and use it in GitHub Desktop.
Bulk delete empty taxonomy terms [Wordpress]
This file contains 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
function delete_empty_terms(){ | |
$taxonomy_name = 'city'; | |
$terms = get_terms( array( | |
'taxonomy' => $taxonomy_name, | |
'hide_empty' => false | |
) ); | |
foreach ( $terms as $term ) { | |
$term_count = $term->count; | |
if ($term_count < 1){ wp_delete_term($term->term_id, $taxonomy_name); | |
} | |
} | |
} | |
add_action( 'wp_head', 'delete_empty_terms' ); |
Hi Sabrina, nice seeing this piece of code.
After some brainstorming, I have found that it's quicker to retrieve all terms (which are not empty), then exclude them from the wp term query (with hide empty to false) which may retrieve only empty terms.
Then looping on them to bulk delete, like so: https://gist.github.com/MaximeCulea/b8f31213e98874befd6a10b702558287
I wish you a wonderful end of the year and happy holidays!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you for sharing this snipet