I’m the developer of the Advanced Custom Fields plugin and am hoping you can help me out with an issue I am facing.
I have a button where you can edit an image. This button will launch a WP 3.5 media modal via the wp_media() function.
The problem is that I want to pre-select an image so that it’s details are loaded in the sidebar panel.
Currently I am hooking into the ‘open’ callback and running some code which populates this selection, however, it is clunky and in efficient. This is what it looks like:
// _media is an object I am using
_media.frame = wp.media({
title : 'title',
multiple : false,
button : { text : 'button' }
});
// open
_media.frame.on('open',function() {
// add class
_media.frame.$el.closest('.media-modal').addClass('acf-media-modal acf-expanded');
// set selection
var selection = _media.frame.state().get('selection'),
attachment = wp.media.attachment( id );
attachment.fetch();
selection.add( attachment );
});
// Finally, open the modal
_media.frame.open();
This is working fine, until the user opens another modal window, selects the upload tab, then uses the edit button which I have created. Now the code fails completely becuase my code relies on the modal being in the ‘browse’ mode.
I found some code which will swap the frame over to the browse mode, it looks like this:
_media.frame.content.mode('browse');
This works some of the time, but then the following code fails. Like it needs some time to render before the attachment can be added to the selection….
Surely there is a better way.
Thanks for your help.
Elliot
Here is the script:
Iâm using the function
loadImages
in following script to load the existing attached images via AJAX and then just pass the function with the IDs of images and it opens up a pre-populated modal.And here is the php function that handles the AJAX request:
I just copied the snippet from my WordPress framework, hope it makes sense.