Copy Posts to Another Network Site
Adds a "Copy to site" bulk action on the Posts screen that copies the selected posts (title, content, excerpt and featured image URL as a note) as drafts to another site you are an editor on.
Opens WPIDE on
Code
if ( ! is_multisite() ) {
return;
}
add_filter( 'bulk_actions-edit-post', function ( $actions ) {
foreach ( get_blogs_of_user( get_current_user_id() ) as $blog ) {
if ( (int) $blog->userblog_id !== get_current_blog_id() ) {
/* translators: %s: site name */
$actions[ 'wpide_copy_to_' . (int) $blog->userblog_id ] = sprintf( __( 'Copy to: %s' ), $blog->blogname );
}
}
return $actions;
} );
add_filter( 'handle_bulk_actions-edit-post', function ( $redirect, $action, $post_ids ) {
if ( 0 !== strpos( $action, 'wpide_copy_to_' ) ) {
return $redirect;
}
$target = absint( substr( $action, strlen( 'wpide_copy_to_' ) ) );
if ( ! $target || ! is_user_member_of_blog( get_current_user_id(), $target ) ) {
return $redirect;
}
$copies = array();
foreach ( array_map( 'absint', $post_ids ) as $post_id ) {
$post = get_post( $post_id );
if ( $post && current_user_can( 'edit_post', $post_id ) ) {
$copies[] = array(
'post_title' => $post->post_title,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'source' => get_permalink( $post ),
);
}
}
$done = 0;
switch_to_blog( $target );
if ( current_user_can( 'edit_posts' ) ) {
foreach ( $copies as $copy ) {
$new = wp_insert_post( array(
'post_title' => $copy['post_title'],
'post_content' => $copy['post_content'],
'post_excerpt' => $copy['post_excerpt'],
'post_status' => 'draft',
'post_author' => get_current_user_id(),
) );
if ( $new && ! is_wp_error( $new ) ) {
update_post_meta( $new, '_wpide_copied_from', esc_url_raw( $copy['source'] ) );
$done++;
}
}
}
restore_current_blog();
return add_query_arg( 'wpide_copied', $done, $redirect );
}, 10, 3 );
add_action( 'admin_notices', function () {
if ( isset( $_GET['wpide_copied'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
$count = absint( $_GET['wpide_copied'] ); // phpcs:ignore WordPress.Security.NonceVerification
/* translators: %d: number of posts */
echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( sprintf( _n( '%d post copied as a draft.', '%d posts copied as drafts.', $count ), $count ) ) . '</p></div>';
}
} );
Notes
Copies are created as drafts. Categories, tags and media are not copied because their IDs differ between sites; the original post's link is saved in a custom field.
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.