Monday, February 26, 2018

WordPress - Add gallery overlay to a metabox using wp.media

Leave a Comment

I'm trying to use a metabox to store a comma separated string of attachment IDs in WordPress.

I have the metabox working fine, but I'm trying to get the wp.media overlay to open in a way that allows the user to select multiple images, and drag and drop order them, then when clicking "select" button, that it puts the string of IDs into the metabox.

Please don't suggest a plugin. I know there are lots of them out there, but I'm building this into a theme and want the bare minimum code.

The JS & PHP I have is this:

jQuery('.custom-post-gallery').on( 'click', function(e){      e.preventDefault();        var image_frame;      if(image_frame){         image_frame.open();      }        // Define image_frame as wp.media object      image_frame = wp.media({          title: 'Select Gallery Images',          library : {              type : 'image'          },          multiple: true      });        image_frame.states.add([          new wp.media.controller.Library({              id:         'post-gallery',              title:      'Select Images for the Post Gallery',              priority:   20,              toolbar:    'main-gallery',              filterable: 'uploaded',              library:    wp.media.query( image_frame.options.library ),              multiple:   image_frame.options.multiple ? 'reset' : false,              editable:   true,              allowLocalEdits: true,              displaySettings: true,              displayUserSettings: true          });      ]);        image_frame.open();  });
<?php      $meta_key = 'custom_post_gallery';      $image_ids = get_post_meta( $post->ID, $meta_key, true );  ?>      <input class="custom-post-gallery" name="<?php echo $meta_key; ?>" type="text" value="<?php echo $image_ids; ?>"/>

This overlay just shows the UI to pick one image, or multiple, if holding control key, but no drag and drop ordering etc. Can I open it in the "gallery" mode somehow? And give it the IDs to use for currently selected images?

Thanks!

1 Answers

Answers 1

If i got you right, you've got text field which open media window on click and you want to insert the id's of the selected images into the field value (id's separated by comma) when clicking on select button. if that so, so this is what i modified:

Fix:

Error because of the semicolon (it is inside an array which can not have semicolon)

    displayUserSettings: true }); // --> here 

Modified:

image_frame variable needs to be set outside this scope and return after reopen action

var image_frame; // --> outside the scope if(image_frame){    image_frame.open();    // --> add return } 

Additions:

Wrap the JS and inject the jQuery as $ sign into the scope, now we can use $ sign instead of jQuery and prevent conflicts with other JS scripts:

(function($){ ... })(jQuery); 

Set the text field object as $that variable so we will be use it inside deeper scopes

var $that = $(this); 

Add the select action and insert the selected images id's separated by comma into the field value:

       image_frame.on( 'select', function() {              var ids = '', attachments_arr = [];              // Get media attachment details from the frame state             attachments_arr = image_frame.state().get('selection').toJSON();             $(attachments_arr).each(function(e){                 sep = ( e != ( attachments_arr.length - 1 ) ) ? ',' : '';                 ids += $(this)[0].id + sep;             });             $that.val(ids);          }); 

All together:

Just the JS part, which was modified:

(function($){      var image_frame;      $('.custom-post-gallery').on( 'click', function(e){          e.preventDefault();          // If the media frame already exists, reopen it.         if (image_frame){            image_frame.open();            return;         }          var $that = $(this);          // Define image_frame as wp.media object         image_frame = wp.media({             title: 'Select Gallery Images',             library : {                 type : 'image'             },             multiple: true         });          image_frame.states.add([             new wp.media.controller.Library({                 id:         'post-gallery',                 title:      'Select Images for the Post Gallery',                 priority:   20,                 toolbar:    'main-gallery',                 filterable: 'uploaded',                 library:    wp.media.query( image_frame.options.library ),                 multiple:   image_frame.options.multiple ? 'reset' : false,                 editable:   true,                 allowLocalEdits: true,                 displaySettings: true,                 displayUserSettings: true             })         ]);          image_frame.open();          image_frame.on( 'select', function() {              var ids = '', attachments_arr = [];              // Get media attachment details from the frame state             attachments_arr = image_frame.state().get('selection').toJSON();             $(attachments_arr).each(function(e){                 sep = ( e != ( attachments_arr.length - 1 ) ) ? ',' : '';                 ids += $(this)[0].id + sep;             });             $that.val(ids);          });      });     })(jQuery); 

This is working for me, tell me if you have any issue.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment