Upload images from one site to another in Multisite

Who would say the solution would be this simple…

After days battling with this, somehow it struck me: “what if we switch_to_blog() inside the media upload iframe?” What if we require the user to save the post before uploading any images?

Turns out I had no answer to why we weren’t doing this on the first place so, having required that the user saved the post before uploading any images, the solution came short and sweet:

1) Add site_id to the GET variables being passed to media-uploader:

<script type="text/javascript">
    jQuery(function(){
            var site_id = <?php echo json_encode($siteid); ?>;
            var post_id = <?php echo json_encode($conteudo->ID); ?>;

                jQuery('.btn_incluir_imagem').click(function() {
                     formfield = jQuery('#upload_image').attr('name');
                     tb_show('', uploader+'media-upload.php?sid='+site_id+'&amp;post_id='+post_id+'&amp;type=image&amp;TB_iframe=true&amp;');
                     return false;
                });

    // More code here
    });
</script>

2) And retrieve it from inside the iframe, right after hooking the scripts and styles:

function admin_styles_scripts_media_upload(){
    // Registers and enqueues


    if($_GET['sid']) { 
        switch_to_blog($_GET['sid']);
    }

    // Any images uploaded here will be directed straight to the post_id inside site_id

}
add_action('admin_print_scripts-media-upload-popup','admin_styles_scripts_media_upload');

This simple trick allows you to upload media from any site to any other site inside a network, so long as you already have the destination’s site_id and post_id. No need to hand-copy files and re-generate metadata, lots of code straight to the garbage can, yay! 🙂

Also, since we’re in an iframe and the only way to get out of it is to close the window, not calling restore_current_blog() doesn’t cause any adverse effects.