Last active
December 28, 2022 22:14
-
-
Save MaximeCulea/b8f31213e98874befd6a10b702558287 to your computer and use it in GitHub Desktop.
Delete empty terms in WP CLI
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 | |
/** | |
* 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