How To Copy Sub-site Media to Admin Site on Upload (WordPress Multisite)

July 16, 2014 by in category Programming, Wordpress tagged as , , , , , with 0 and 1
Home > Blog > Programming > How To Copy Sub-site Media to Admin Site on Upload (WordPress Multisite)

Jaysus, this one took me ages to understand. I spent so long doing all sorts of things to get it to work but in the end I think I’ve copped it. One important note though: do not remove the “restore_current_blog()” function at the end or move it within the if statement. You’ll end up in recursive hell with 50,000 weird ass database entries…

 

<?php

/**
 * Adds all media uploaded to main hub site
 * @param integer $post_ID
 */
function add_to_admin_site( $post_ID ) {
  global $wpdb;

  // This will keep us out of recursion
  if(get_current_blog_id() != 1){
    // Get the last uploaded attachment
    $posts = get_posts(array(
        'post_type'   => 'attachment',
        'posts_per_page' => 1,
        'fields' => 'ids'
        )
    );
    // Get our post meta
    foreach($posts as $p){
        $attachment = get_post_meta($p);
    }

    // Instantiate an empty object for our insert
    $attachmentObject = new stdClass();

    // You can change what the post_title will be but 
    // by default I've set it to just be the attached file
    // directory and file name
    $attachmentObject->post_content = $attachmentObject->post_title = $attachment['_wp_attached_file'][0];
    $attachmentObject->post_status = 'inherit';

    // Get the file extension of the upload
    $extension = substr($attachment['_wp_attached_file'][0], -3, 3);

    // Set correct mime type
    if(strcasecmp('jpg', $extension) == 0 || strcasecmp('jpeg', $extension) == 0){
       $attachmentObject->post_mime_type = 'image/jpeg';
    } else if(strcasecmp('png', $extension) == 0 || strcasecmp('gif', $extension) == 0){
       $attachmentObject->post_mime_type = 'image/'.$extension;
    }

    $blog_id = get_current_blog_id();

    // Switch over to or main site
    switch_to_blog(1);

    // Insert the image
    wp_insert_attachment( $attachmentObject, 'sites/'.$blog_id.'/'.$attachment['_wp_attached_file'][0]);
  }

  // When the hook passes around again,
  // this will restore back to the original blog
  restore_current_blog();
  
}
add_action( 'add_attachment', 'add_to_admin_site' );

?>
© Evan Smith 2009 - 2017