During some data migration tasks, we found we needed to update the term counts for a taxonomy after an import process, but didn't find anything in the built-in commands to do it. I ended up adding the following to our project.
I can refactor this a bit to support multiple taxonomies and other arguments and to a pull request if this is something y'all think would be a good addition to the core CLI term commands.
/**
* Updates the count for all terms in a taxonomy
*
* OPTIONS
*
* <taxonomy>
* Taxonomy slug
*
* ## EXAMPLES
*
* wp terms update-count
*
* @subcommand update-count
*
* @synopsis <taxonomy>
*/
function update_count( $positional_args, $assoc_args = array() ) {
$taxonomy = $positional_args[0];
if ( ! taxonomy_exists( $taxonomy ) ) {
\WP_CLI::Error( "Taxonomy does not exist" );
}
$terms = get_terms( $taxonomy, array( 'hide_empty' => false ) );
$count = count( $terms );
$progress_bar = \WP_CLI\Utils\make_progress_bar( "Updating {$count} terms:", $count, 1 );
$progress_bar->display();
foreach ( $terms as $term ) {
wp_update_term_count( $term->term_taxonomy_id, $taxonomy );
$progress_bar->tick();
}
$progress_bar->finish();
\WP_CLI::Success( "Finished updating term counts" );
}
During some data migration tasks, we found we needed to update the term counts for a taxonomy after an import process, but didn't find anything in the built-in commands to do it. I ended up adding the following to our project.
I can refactor this a bit to support multiple taxonomies and other arguments and to a pull request if this is something y'all think would be a good addition to the core CLI term commands.