Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active December 28, 2022 22:17
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sabrina-zeidan/d812d794998f1a1c56029d54df435caa to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/d812d794998f1a1c56029d54df435caa to your computer and use it in GitHub Desktop.
Bulk delete empty taxonomy terms [Wordpress]
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' );
@zarankumar
Copy link

thank you for sharing this snipet

@MaximeCulea
Copy link

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