Skip to content

Instantly share code, notes, and snippets.

@MattPostlethwaite
Created October 11, 2017 08:01
Show Gist options
  • Save MattPostlethwaite/67a6595bf6beb4bccd8e317cabdd88f9 to your computer and use it in GitHub Desktop.
Save MattPostlethwaite/67a6595bf6beb4bccd8e317cabdd88f9 to your computer and use it in GitHub Desktop.
WP-CLI: Save terms command
<?php
/**
* Save taxonomy terms.
*
* ## OPTIONS
*
* <taxonomy>
* : Taxonomy of terms to be saved.
*
* [--dry-run]
* : Dry run only, no terms will be updated.
*
* ## EXAMPLES
*
* wp save terms product_tag run --another="yes"
*/
$save_terms_cmd = function($args, $assoc_args) {
$tax = $args[0];
$dry_run = null;
if( array_key_exists('dry-run', $assoc_args) )
$dry_run = $assoc_args['dry-run'];
$args = array(
'post_type' => 'product',
'taxonomy' => $tax,
'post_per_page' => -1
);
$terms = get_terms($args);
if( !empty($terms) && !is_wp_error($terms) ) {
// Loop through all found terms
foreach ($terms as $t) :
echo $t->name . "\n";
// Only make changes if not a dry run
if( !$dry_run )
mp_update_term( $t->term_id, $tax );
endforeach;
} else {
// No taxonomy terms found
WP_CLI::error( "No $tax terms found.\n" );
}
// Closing message
if(!$dry_run) :
echo "\n";
WP_CLI::success( "All $tax terms saved\n" );
else :
echo "\n";
WP_CLI::success( count($terms) . " $tax terms found." );
WP_CLI::success( "Dry run complete for $tax (Nothing Changed)\n" );
endif;
};
WP_CLI::add_command( 'save terms', $save_terms_cmd );
/**
* Function mp_update_term()
* @param int $t Term ID
* @param string $tax Taxonomy
*/
function mp_update_term($t, $tax) {
wp_update_term( $t, $tax );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment