Copy posts from one blog to another in multisite environment

I am creating a plugin for post.php page where user can select (one or more) blogs and copy the post content,title,author,categories everything in selected blogs. The copied post would be the child of original post and now the original post would be parent post.

I want to know that is there any WP function which can directly take care of copy posts to other multisite blogs or what would be the best function to do it.

Related posts

Leave a Reply

2 comments

  1. To copy a post from one blog to another you can do something like this:

    function copy_post_to_blog($post_id, $target_blog_id) {
    
       $post = get_post($post_id, ARRAY_A); // get the original post
    
       $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
    
       restore_current_blog(); // return to original blog
    }
    
  2. You solution is good, but it doesn’t cover taxonomies and post metas, so my recommend to checkout out this solution https://rudrastyh.com/wordpress-multisite/move-posts-between-blogs.html

    So, first of all we get all post data get_post($post_id, ARRAY_A); all post’s categories and post metas, after that we switch to a correct blog with switch_to_blog($target_blog_id); and create new post and update all its data + terms + post meta. Then restore_current_blog();