Bulk Duplicate Posts and Pages as Drafts
Adds a "Duplicate as draft" bulk action to post and page lists that copies the selected items with their content, categories, tags and custom fields into new drafts.
Opens WPIDE on
Code
$wpide_bulk_dup_types = array( 'post', 'page' );
foreach ( $wpide_bulk_dup_types as $wpide_type ) {
add_filter( "bulk_actions-edit-{$wpide_type}", function ( $actions ) {
$actions['wpide_duplicate'] = 'Duplicate as draft';
return $actions;
} );
add_filter( "handle_bulk_actions-edit-{$wpide_type}", function ( $redirect, $action, $post_ids ) {
if ( 'wpide_duplicate' !== $action ) {
return $redirect;
}
$done = 0;
foreach ( $post_ids as $post_id ) {
$post = get_post( $post_id );
if ( ! $post || ! current_user_can( 'edit_post', $post_id ) ) {
continue;
}
$new_id = wp_insert_post( wp_slash( array(
'post_type' => $post->post_type,
'post_status' => 'draft',
'post_title' => $post->post_title . ' (Copy)',
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_parent' => $post->post_parent,
'menu_order' => $post->menu_order,
'post_password' => $post->post_password,
'comment_status' => $post->comment_status,
'ping_status' => $post->ping_status,
'post_author' => get_current_user_id(),
) ), true );
if ( is_wp_error( $new_id ) ) {
continue;
}
foreach ( get_object_taxonomies( $post->post_type ) as $taxonomy ) {
wp_set_object_terms( $new_id, wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'ids' ) ), $taxonomy );
}
foreach ( get_post_meta( $post_id ) as $key => $values ) {
if ( in_array( $key, array( '_edit_lock', '_edit_last', '_wp_old_slug' ), true ) ) {
continue;
}
foreach ( $values as $value ) {
add_post_meta( $new_id, $key, wp_slash( maybe_unserialize( $value ) ) );
}
}
$done++;
}
return add_query_arg( 'wpide_duplicated', $done, $redirect );
}, 10, 3 );
}
add_action( 'admin_notices', function () {
if ( ! empty( $_GET['wpide_duplicated'] ) ) {
printf( '<div class="notice notice-success is-dismissible"><p>Created %d draft copies.</p></div>', absint( $_GET['wpide_duplicated'] ) );
}
} );
Notes
Copies are owned by you and titled "(Copy)"; comments and revisions are not copied.
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.