Skip to content

Instantly share code, notes, and snippets.

@MaximeCulea
Last active December 28, 2022 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaximeCulea/b8f31213e98874befd6a10b702558287 to your computer and use it in GitHub Desktop.
Save MaximeCulea/b8f31213e98874befd6a10b702558287 to your computer and use it in GitHub Desktop.
Delete empty terms in WP CLI
<?php
/**
* Delete all empty terms for the given $taxonomy
* PS: You can do the same in WP CLI or even plain WordPress php functions
*
* @param : string $tax : given taxonomy to work on
*
* @author Maxime CULEA
*/
function delete_empty_terms( $tax = 'category' ) {
$args = [
'taxonomy' => $tax,
'fields' => 'ids',
];
$term_ids_not_empty = get_terms( $args );
if ( empty( $term_ids_not_empty ) ) {
return;
}
$term_ids_empty = get_terms( wp_parse_args( $args, [
'hide_empty' => false,
'exclude' => $term_ids_not_empty,
] ) );
if ( empty( $term_ids_empty ) ) {
return;
}
foreach ( $term_ids_empty as $term_id ) {
\WP_CLI::runcommand( sprintf( 'term delete %s %d', $tax, $term_id ), [ 'exit_error' => false ] );
}
\WP_CLI::runcommand( sprintf( 'term recount %s', $tax ), [ 'exit_error' => false ] );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment