Skip to content

Instantly share code, notes, and snippets.

@murdaugh
Created October 3, 2013 20:11
Show Gist options
  • Save murdaugh/6816345 to your computer and use it in GitHub Desktop.
Save murdaugh/6816345 to your computer and use it in GitHub Desktop.
Copies a post (as well as its associated meta data) from one wordpress blog to another on the same network.
<?php
function copy_post_to_blog($post_id, $target_blog_id) {
$post = get_post($post_id, ARRAY_A); // get the original post
$meta = get_post_meta($post_id);
$post['ID'] = ''; // empty id field, to tell wordpress that this will be a new post
switch_to_blog($target_blog_id); // switch to target blog
$inserted_post_id = wp_insert_post($post); // insert the post
foreach($meta as $key=>$value) {
update_post_meta($inserted_post_id,$key,$value[0]);
}
restore_current_blog(); // return to original blog
}
?>
@Lukapotamus
Copy link

Hey Murdaugh,

Happy New Year!

This is a great piece of code! Do you know how I would go about ignoring just one piece of the metadata but copying everything else?

Kind Regards

Luke Pope

@msherstobitow
Copy link

@Lukapotamus, you can modify foreach-loop like this, add at the beginning of the loop body:

if ( 'some_value' === $key ) { continue; }

@roly151
Copy link

roly151 commented Dec 9, 2022

Can someone share how to also copy the posts tags and categories?

I currently have:

$post_categories = wp_get_post_categories( $original_post_id ); $post_tags = wp_get_post_tags( $original_post_id, array( 'fields' => 'names' ) );

and then within the switch to blog part:

$categories = wp_set_post_categories( $inserted_post_id, $post_categories); $tags = wp_set_post_tags( $inserted_post_id, $post_tags );

But this is not working

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment