Posterous theme by Cory Watilo

Sharing media libraries across network sites in WordPress

Media_httpiimgurcom6h_awvxb

This is part of a larger project I’m developing at work.

The ultimate goal is to have a central blog where the department can serve up sanctioned images, video, and audio for students to use on their portfolios – also hosted in the same WordPress multisite network. After realizing that a (good) solution does not yet exist, I set out to create my own.

The first hurdle was to create a new tab in the Upload/Insert media page. This task was made easy by a great tutorial here.

The second and most difficult hurdle was solved by looking through the core code. I was looking for an existing function that handled the entire functionality of the media library. Eventually I found it in wp-admin/includes/media.php on line 822. The function is called media_upload_library().

Now for the last step. Plugging media_upload_library() into my code will only create a duplicate media library for the blog I am currently editing. To load a library from a different blog I need one last function. Before calling media_upload_library(), I call up another useful core WP function switch_to_blog($int) where $int is the blog ID number. This number can be found in the WP database.

I haven’t yet had a chance to thoroughly test this code. I’ve only tested this on sites where I am an admin so I’m sure I will run into trouble when I test it as a low-level user. If you have any suggestions, please let me know.

Here’s the code so far:

// Add filter that inserts our new tab
function nsm_menu($tabs) {
  $newtab = array('shared_media' => __('Network Shared Media', 'networksharedmedia'));
  return array_merge($tabs, $newtab);
}
add_filter('media_upload_tabs', 'nsm_menu');

// Load media_nsm_process() into the existing iframe
function nsm_menu_handle() {
  return wp_iframe('media_nsm_process');
}
add_action('media_upload_shared_media', 'nsm_menu_handle');

/*
 * media_nsm_process() contains the code for what you want to display. This function MUST start with the word 'media' in order
 * for the proper CSS to load.
 *
 * First, we switch to the blog containing all of the media. This is called up by the blog # found in the database.
 *
 * Then we call media_upload_library() which contains all of the code needed to show the library, select media sizes, and
 * insert into the post.
 */
 function media_nsm_process() {
   switch_to_blog(3);
   media_upload_library();
 }

Take a look at the follow-up post.