Move All Posts From One Author to Another (WP-CLI)
Adds a "wp reassign-posts" command that hands every post of one user to another user, for example when a writer leaves, without deleting the old account.
Opens WPIDE on
Code
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'reassign-posts', function ( $args, $assoc_args ) {
$find = function ( $value ) {
$field = is_numeric( $value ) ? 'id' : ( is_email( $value ) ? 'email' : 'login' );
$user = get_user_by( $field, $value );
if ( ! $user ) {
WP_CLI::error( sprintf( 'User "%s" not found.', $value ) );
}
return $user;
};
$from = $find( $args[0] );
$to = $find( $args[1] );
$ids = get_posts( array(
'author' => $from->ID,
'post_type' => isset( $assoc_args['post_type'] ) ? array_map( 'sanitize_key', explode( ',', $assoc_args['post_type'] ) ) : 'any',
'post_status' => 'any',
'posts_per_page' => -1,
'fields' => 'ids',
'no_found_rows' => true,
) );
if ( ! empty( $assoc_args['dry-run'] ) ) {
WP_CLI::log( sprintf( '%d posts would move from %s to %s.', count( $ids ), $from->user_login, $to->user_login ) );
return;
}
$progress = WP_CLI\Utils\make_progress_bar( 'Reassigning', count( $ids ) );
foreach ( $ids as $id ) {
wp_update_post( array( 'ID' => $id, 'post_author' => $to->ID ) );
$progress->tick();
}
$progress->finish();
WP_CLI::success( sprintf( 'Moved %d posts from %s to %s.', count( $ids ), $from->user_login, $to->user_login ) );
}, array(
'shortdesc' => 'Moves all posts from one author to another.',
'synopsis' => array(
array( 'type' => 'positional', 'name' => 'from', 'description' => 'Current author (ID, login or email).' ),
array( 'type' => 'positional', 'name' => 'to', 'description' => 'New author (ID, login or email).' ),
array( 'type' => 'assoc', 'name' => 'post_type', 'optional' => true ),
array( 'type' => 'flag', 'name' => 'dry-run', 'optional' => true ),
),
) );
Notes
Users can be given by ID, login or email; add --post_type=page to limit it and --dry-run to preview.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.