Shiba

Adventures in WordPress

  • — Home —
  • Dog
  • Art
  • Contact
  • WordPress Articles
    • WP Plugins
    • WP Programming
    • WP Admin Panels
    • WP Theme Design
    • WP How-To
    • WP Theme Images
You are here: Home / WordPress Programming / How to Add the WordPress 3.5 Media Manager Interface – Part 2

How to Add the WordPress 3.5 Media Manager Interface – Part 2

Tweet

by ShibaShake 29 Comments

In Part-1 of this series, we described how to add a simple media manager popup for selecting an image. In addition to image selection, there are many other useful media manager functions, for example, the gallery editing interface.

In this article, we explore how to access and customize some of these additional media manager functions. In particular, we want to add the Edit Gallery function, from the media manager interface, into our Media Library plugin. We describe how to do that here.

Custom-Header.js File

We can get a lot of insight into how to create a media manager frame by looking at the custom-header.js file. Of particular interest, is the line which contains –

frame = wp.media.frames.customHeader = wp.media({ ... });

This is where the media manager frame gets created. We can do some simple customization to the frame by setting various attributes in the wp.media function call.

For example, in the custom-header.js file, we customize the title, library (type), and button of the media manager frame.

1. Create Our Own Media Manager Frame

To more fully customize our media manager interface, we start by creating our own frame (similar to what was done in the custom-header.js file.

wp.media.shibaMlibEditGallery = {
	
	frame: function() {
		if ( this._frame )
			return this._frame;

		this._frame = wp.media({
			id:			'my-frame',				   
			frame:     	'post',
			state:     	'gallery-edit',
			title:     	wp.media.view.l10n.editGalleryTitle,
			editing:   	true,
			multiple:  	true,
		});
		return this._frame;
	},

	init: function() {
		$('#upload-and-attach-link').click( function( event ) {
			event.preventDefault();

			wp.media.shibaMlibEditGallery.frame().open();

		});
	}
};

$(document).ready(function(){
	$( wp.media.shibaMlibEditGallery.init );
});

Line 9 – We set the frame type. There are two types of pre-built frames in WordPress 3.5 – post and select. Select is the default frame type and it is the interface that is created in the custom-header.js file.

The post frame is what appears when we click on the Add Media button while editing posts or pages.

For more detail on these two frame types, we can look at MediaFrame.Post and MediaFrame.Select in the wp-includes/js/media-views.js file.

Line 10 – We set the state to ‘gallery-edit’ so that when we open the media manager interface, we are on the edit gallery screen.

Line 11 – Use the default edit gallery screen title.

Line 12 – Allow gallery to be edited.

Line 13 – Allow multiple images to be selected.

Line 19 – Bind the frame to an interface button. In this case, we open the media manager interface when our HTML button with id=”upload-and-attach-link” gets clicked.

Line 20 – Do not allow the click to do anything else.

Line 22 – Open our media manager frame.

When we click on our #upload-and-attach-link button, we get the media-manager frame below.

Edit Gallery media manager frame.
Edit Gallery media manager frame.

2. Get Initial Gallery Images

Note that the Edit Gallery frame above always appears as blank. To fill the frame with an initial set of images, we must set the selection attribute while creating our frame.

		var selection = this.select();
		this._frame = wp.media({
			id:			'my-frame',				   
			frame:     	'post',
			state:     	'gallery-edit',
			title:     	wp.media.view.l10n.editGalleryTitle,
			editing:   	true,
			multiple:  	true,
			selection: 	selection
		});

We must also write the select function to create a selection of images. One common way to populate our gallery is through its gallery shortcode. There is already code that does this in the media-editor.js file. Below, we adapt the native code for our own purposes.

	// Gets initial gallery-edit images. Function modified from wp.media.gallery.edit
	// in wp-includes/js/media-editor.js.source.html
	select: function() {
		var shortcode = wp.shortcode.next( 'gallery', wp.media.view.settings.shibaMlib.shortcode ),
			defaultPostId = wp.media.gallery.defaults.id,
			attachments, selection;

		// Bail if we didn't match the shortcode or all of the content.
		if ( ! shortcode )
			return;

		// Ignore the rest of the match object.
		shortcode = shortcode.shortcode;

		if ( _.isUndefined( shortcode.get('id') ) && ! _.isUndefined( defaultPostId ) )
			shortcode.set( 'id', defaultPostId );

		attachments = wp.media.gallery.attachments( shortcode );
		selection = new wp.media.model.Selection( attachments.models, {
			props:    attachments.props.toJSON(),
			multiple: true
		});
		
		selection.gallery = attachments.gallery;

		// Fetch the query's attachments, and then break ties from the
		// query to allow for sorting.
		selection.more().done( function() {
			// Break ties with the query.
			selection.props.set({ query: false });
			selection.unmirror();
			selection.props.unset('orderby');
		});

		return selection;
	},

This select function returns a wp.media.model.Selection object that contains all the images for the shortcode string that is defined in wp.media.view.settings.shibaMlib.shortcode.

We previously set this variable (in php) by hooking into the media_view_settings filter. This filter is used to pass attributes from our server (php) into the media manager interface (javascript).

add_filter( 'media_view_settings', array($this, 'media_view_settings'), 10, 2 );

function media_view_settings($settings, $post ) {
	if (!is_object($post)) return $settings;

    // Create our own shortcode string here
	$shortcode = ...

	$settings['shibaMlib'] = array('shortcode' => $shortcode); 
	return $settings;
}

Once we define a selection, our Edit Gallery menu will start with our defined set of images (shown below).

Populate our Edit Gallery menu using a gallery shortcode.
Populate our Edit Gallery menu using a gallery shortcode.

3. Specify Our Frame Update Function

Now, all we need to do, is to write our own update function for when we click on the Update Gallery button.

		this._frame.on( 'update', 
					   function() {
			var controller = wp.media.shibaMlibEditGallery._frame.states.get('gallery-edit');
			var library = controller.get('library');
			// Need to get all the attachment ids for gallery
			var ids = library.pluck('id');
		
			// send ids to server
			wp.media.post( 'shiba-mlib-gallery-update', {
				nonce:  	wp.media.view.settings.post.nonce, 
				html:   	wp.media.shibaMlibEditGallery.link,
				post_id: 	wp.media.view.settings.post.id,
				ids: 		ids
			}).done( function() {
				window.location = wp.media.shibaMlibEditGallery.link;
			});

		});

Lines 3-6 – Extract the list of image-ids associated with our current Edit Gallery menu.
Lines 8-14 – Send the list of image-ids to the server to be processed. ‘shiba-mlib-gallery-update’ is our own AJAX function id. We can link our own server function to it, by doing the following.

add_action( 'wp_ajax_shiba-mlib-gallery-update', 
		   array($this,'wp_ajax_shiba_mlib_gallery_update'));

Lines 15 – Refresh our gallery object screen once we finish our AJAX function call.

We can add our update bind-event to our earlier frame creation function. For example, right before

return this._frame;

We Are Done!

We can use the process above to access other post frame menus, customize update operations, and further customize the media manager interface according to our needs.

Related Articles

How to Add the WordPress 3.5 Media Manager Interface

A tutorial on how to add the new WordPress 3.5 media manager interface into our own plugin or theme.

How to Add the Media Manager Menu to the Theme Preview Interface

WordPress 3.4 added a great theme preview interface that allows us to easily customize theme options (colors, images, menus, and more), as well as quickly view those updates on a theme preview frame. WordPress 3.5 added a new media manager interface that is fast, easy to use, and awesome to look at. In this article, we consider how to bring those two interfaces together so that we can use images from our media library in the theme preview interface. 1. Create an Image Control I start [...]

How to Hook into the Media Upload Popup Interface

What is the media upload popup interface? That is simply the popup window that appears when we click on the Add Media button (for adding images and video) while in the Edit Post screen. The same interface is also currently being used for - Setting featured images in posts, and Setting header images in a theme. It can also be very useful in a plugin. For example, my Shiba Gallery plugin uses the Media Upload Interface to assign a default picture for posts and pages that do not have [...]

Comments

  1. Janine says

    August 26, 2019 at 6:36 pm

    Still relevant in 2019.

    Reply
  2. ledock says

    July 4, 2016 at 7:09 am

    To every people who are stucked, as i was, since two days. (i use WordPress 4.5.3)

    Replace : if (!is_object($post)) return $settings;

    By: if ( isset( get_current_screen()->post_type ) && (get_current_screen()->post_type == ‘YOUR POST TYPE’ ) ) {
    $post = get_post( $_GET[‘post’] );
    }

    Explanation: If you use a custom post type like i was ‘$post’ will always be a non-object and you’re not gonna be able to pass the if.

    —
    For those who don’t get how to have a shortcode string, that’s simple. Juste use a basic shortcode like : [gallery ids="729,732,731,720"]. The numbers are ids of attachments you want to show.

    Here is my personal code. It’s not gonna resolve all issues but it’s easily adaptable:

    $imageIdsArray = json_decode(get_post_meta($post->ID, “_gallery_medias_ids”, true));

    // i previously saved my images using json_encode (to transform my array of // ids into a string like ‘[729,732]’ in database

    if( !empty( $imageIdsArray ) ) {
    $imageIds = implode($imageIdsArray, ‘ , ‘);
    $shortcode = ‘[gallery ids="'. $imageIds .'"]‘;
    $settings[‘myGallery’] = array(‘shortcode’ => $shortcode);
    }
    return $settings;

    —
    Finally in your .js file put:
    var shortcode = wp.shortcode.next( ‘gallery’, wp.media.view.settings.myGallery.shortcode )

    And you’ll be fine 🙂

    —
    Thanks to the author ! You made the most comprehensible documentation about wp.media manipulation and i’m writing this comment in 2016 (!!)

    Reply
  3. Lorenzo says

    October 27, 2014 at 2:07 am

    Hi realy a good tutorian thank you 🙂
    A question, I wuold like to keep the “select a file” button open even when there are file already loaded in the mediamanager. Is there a way to do this?
    Thank you

    Reply
  4. Cyrus David says

    August 23, 2014 at 10:58 pm

    Hi, I got lost at this part:

    // Create our own shortcode string here
    $shortcode = ...

    How do I generate the shortcode?

    Reply
  5. bean says

    July 21, 2014 at 6:43 pm

    Nice tutorial ShibaShake.

    I’m stuck with this:
    wp.media.post( ‘shiba-mlib-gallery-update’, {
    nonce: wp.media.view.settings.post.nonce,
    html: wp.media.shibaMlibEditGallery.link,
    post_id: wp.media.view.settings.post.id,
    ids: ids
    }).done( function() {
    window.location = wp.media.shibaMlibEditGallery.link;
    });

    and this:
    add_action( ‘wp_ajax_shiba-mlib-gallery-update’,
    array($this,’wp_ajax_shiba_mlib_gallery_update’));

    wp.media.shibaMlibEditGallery.link returns undefined.

    Do you mind giving an example setting of wp.media.shibaMlibEditGallery.link and implementation of wp_ajax_shiba_mlib_gallery_update.

    I really appreciate it so much. Thanks again 🙂

    Reply
  6. Jeremy says

    July 8, 2014 at 10:05 am

    Nice tutorial, thanks. Helped me fix an issue in my plugin. 😉

    Reply
  7. Lukas Doubek says

    February 5, 2014 at 5:25 am

    Hi, nice article, im running the media uploader window from a colorbox modal window, which i set to 90%width, and inside i have button which trigger the media uploader.
    but when i trigger it, it everytime opens smaller than the parent colorbox modal.
    where can i set the width and height for the window with media uploader?
    thanks for reply.

    Reply
  8. Sascha says

    December 30, 2013 at 7:02 pm

    Hi there,

    I do not properly understand the 2nd part (2. Get Initial Gallery Images) at all. I am not using your plugin/theme, but want to use the code on the front end. I mastered step 1 ok – so I get the media modal, but there are no proper explanations for step 2. I would like to only show the uploaded images to the post that is just being viewed. Is there a good way to do this? Apart from that the explanations are very detailed and very helpful!
    Thanks,
    Sascha

    Reply
  9. aditia says

    November 19, 2013 at 1:26 am

    i get error when adding this code
    wp.media.view.settings.shibaMlib.shortcode
    please help

    Reply
  10. Michael Kastiel says

    November 4, 2013 at 2:22 pm

    Hi
    Thank you for making this tutorial!
    I get an error when I try to add the shortcode:

    TypeError: ‘undefined’ is not an object (evaluating ‘wp.media.view.settings.shibaMlib.shortcode’)
    select (media-uploader.js, line 23)
    frame (media-uploader.js, line 9)
    (anonymous function) (media-uploader.js, line 61)
    dispatch (load-scripts.php, line 4)
    handle (load-scripts.php, line 4)

    Can you please help me?
    Thanks
    Michael

    Reply
  11. Pratik says

    October 6, 2013 at 10:46 pm

    Thankyou Shiba for this great tutorial that really helped me

    Reply
  12. maged ali says

    August 18, 2013 at 2:37 pm

    this is a great tutorial but can i insert the images ids to text input how to make it?
    thanks 🙂

    Reply
  13. Jeremy says

    July 26, 2013 at 11:48 pm

    Hi,

    As ppahppp, I managed to make all the first part (which is not much) to integrate the media manager in my theme, but come the second part can not can not read the shortcode …

    Uncaught TypeError: Can not read property ‘shortcode’ of undefined.

    And I can not find a solution.

    Anyway I tried your plugin and it is really well done, but there are too many options for what I need, this is why I just rewritten my theme. Finally, when I could do it.

    Reply
  14. ppahppp says

    May 31, 2013 at 6:29 am

    add_filter( ‘media_view_settings’, array($this, ‘media_view_settings’), 10, 2 );
    hi all
    i got as far as 2. Get Initial Gallery Images but cant get the php to pass to the js. Im pretty new to this but it definatly seems im missing something small. I tried replacing the wp.media.view.settings.shibaMlib.shortcode with ‘[gallery ids=192,193,194,195]‘ and it works but the line $shortcode = ‘[gallery ids=192,193,194,195]‘; dosnt seem to do anything.
    Help me please, driving me crazy

    function media_view_settings($settings, $post ) {
    if (!is_object($post)) return $settings;

    // Create our own shortcode string here
    $shortcode = …

    $settings[‘shibaMlib’] = array(‘shortcode’ => $shortcode);
    return $settings;
    }

    Reply
    • Phil Johnston says

      December 8, 2013 at 5:35 pm

      If you are using a Custom Post Type you may need to take out this line:

      if (!is_object($post)) return $settings;

      Reply
      • thuan says

        November 5, 2015 at 10:13 pm

        thanks you.

        Reply
  15. wp says

    May 26, 2013 at 8:28 pm

    hai, its great to find this , but i got some error found using google chrome ,

    “Uncaught TypeError: Cannot set property ‘shibaMlibEditGallery’ of undefined ”

    i’m still new with this

    Reply
    • noob says

      June 28, 2013 at 6:58 am

      anyone find an answer to this

      Reply
  16. BASTA! says

    April 12, 2013 at 1:02 pm

    Shibashake, where did you ***GET*** the knowledge you are sharing here? It appears this whole wp.media thing is COMPLETELY UNDOCUMENTED – did you just study the source code? Is that all I’m left with if I change one tiny little option in your example and everything falls apart and there is no documentation to tell me why?

    Reply
    • BASTA! says

      April 12, 2013 at 1:03 pm

      Ouch, nevermind, read-all-comments FAIL on my part.

      Reply
  17. hittheroadjack says

    March 15, 2013 at 10:08 am

    Absolutely great stuff!
    After a couple of experiments, I was able to understand what’s going on in this article and adopted it for one of my installations.
    Seems like you have more background information on this! Is there any kind of reference (other than the WP core scripts) to learn about the parameters used in the wp.media and underlaying objects? As it looks by now, the WP core dev team does not provide any information on that – or I simply did not find it.

    Reply
    • ShibaShake says

      March 15, 2013 at 10:31 am

      I got everything from the core scripts. Haven’t found other reference materials as of yet.

      Reply
  18. Kim says

    March 2, 2013 at 8:00 pm

    Nice article! Do you know how to make it possible to control what type of files can be entered into the gallery? For example to create a document list of something like that.

    Reply
    • ShibaShake says

      March 7, 2013 at 10:19 am

      Yeah, this is something that I am thinking of adding to one of my plugins. Haven’t had the time to look into it yet.

      Reply
  19. Enrique says

    January 18, 2013 at 4:48 pm

    Thank you for a great post on a topic that so far has very little coverage and seems to be baffling to most: the WordPress 3.5 Media Library. I’ve been looking into the possibility of adding filtering by taxonomy to the Media Library interface, but so far the depth of it is overwhelming!

    Reply
  20. keoshi says

    January 11, 2013 at 8:43 am

    Hi,

    Great explanation! thanks for sharing.

    I have a question. How I can get the default instance of the media manager which opens with the “Add Media” button?

    I need to get the model of the “single” selection that opens in the sidebar so I can build a link with the model information then insert a button that opens a modal.

    Reply
    • keoshi says

      January 11, 2013 at 9:37 am

      update: I managed to get the default frame using
      var frame = wp.media.editor.add(‘content’);
      frame.open() // opens the default media manager

      But still can’t get the single attachment selected which opens in the sidebar

      Reply
      • ShibaShake says

        January 14, 2013 at 12:08 pm

        In media-view.js, in the media.controller.FeaturedImage object, updateSelection function, this is what they do to select an item-

        var selection = this.get('selection');
        selection.reset( attachment ? [ attachment ] : [] );
        
        Reply

Leave a Reply to ppahppp Cancel reply

Your email address will not be published.

Recent Posts

  • Screen-shot of mobile responsive Poll Daddy object, where text floats properly to the right of radio buttons.How to Make Poll Daddy Objects Mobile Responsive
  • Screen-shot of blog post with no page border (flowing design).Genesis Skins 1.5
  • Screen-shot of the media manager Create-Gallery screen, while doing a post search.Shiba Media Library 3.7
  • Screenshot of the Edit Gallery screen after we hit the Create Gallery button.How to Expand the WordPress Media Manager Interface
  • Blonde girl looking through and holding a circular picture frame.Shiba Gallery 4.3
  • Close-up of beautiful blonde holding a square picture frame.Google Authorship - Good or Bad for Search Traffic?
  • Shiba Widgets 2.0
  • Media Temple screenshot of editing my sub-domain DNS entry.Using CDN Cnames with w3tc and MultiSite
  • Shiba Skins WordPress ThemeShiba Skins WordPress Theme
  • How to add the Media Manager Menu to the Theme Preview InterfaceHow to Add the Media Manager Menu to the Theme Preview Interface

Recent Comments

  • Populate our Edit Gallery menu using a gallery shortcode.How to Add the WordPress 3.5 Media Manager Interface – Part 2 (29)
    • Janine
      - Still relevant in 2019.
  • Update custom inputs with the proper data using Javascript.Expand the WordPress Quick Edit Menu (57)
    • PhoenixJP
      - Thanks for this tutorial. Does someone knows if this still work with wordpress 5.03 and 5.1.
    • Francine Carrel
      - This is a very long time away from your original comment, but did you ever work it out? I am stuck on the exact same thing ...
  • WordPress Search Widget – How to Style It (55)
    • TelFiRE
      - How do you style the "X" that shows up when you start typing?
  • WordPress Excerpt – How to Style It (36)
    • James
      - Great post. I really need some help. I have set border lines around my excerpts on my blog page/post page. The problem is ...
  • Add Custom Taxonomy Tags to Your WordPress Permalinks (123)
    • Darshan Saroya
      - Update permalinks. Go to settings > permalink and just save it.
    • Darshan Saroya
      - I want to access two different types of taxonomies like city and room, how can I access it via wp permalink?
  • How to Selectively Load Plugins for Specific Pages (6)
    • cla
      - Perfect! But at first I was misled, I thought the path / wordpress-theme / was an your alias of / theme .. and nothing happened.. ...
    • Aeros
      - Hi, I have tried your way. My problem is i'm using boilerplate to most of my plugins. When i tried to include the plugin ...
  • Write a Plugin for WordPress Multi-Site (44)
    • An Quach
      - I always use single site because it's easy for me to managed. When I need another worpdress on subdomain or subfolder, I ...

Copyright © 2019 · Genesis Skins by ShibaShake · Terms of Service · Privacy Policy ·