我正在使用自定义帖子类型,在其中添加了自定义元框。在自定义元框中,我尝试为多个图像添加媒体上传器。使用这个上传器,我想在一个数组中存储多个图像ID。问题是,即使选择多个图像,我也只能保存一个ID。

我真的希望有人能帮助我。

我的JS:

    jQuery(document).ready(function(){
  var addButton = document.getElementById('last-opp-bilde');
  var deleteButton = document.getElementById('fjern-bilde');
  var img = document.getElementById('image-tag');
  var hidden = document.getElementById('img-hidden-field');
  var imageUploader = wp.media({
    title: 'Velg bilde',
    button: {
      text: 'Bruk dette bildet'
    },
    multiple: true
  });

  addButton.addEventListener( 'click', function() {
    if (imageUploader) {
      imageUploader.open();
    }
  });

  imageUploader.on( 'select', function() {
    var attachment = imageUploader.state().get('selection').first().toJSON();
    img.setAttribute( 'src', attachment.url);
    img.setAttribute( 'style', 'width: 50%;');
    hidden.setAttribute( 'value', JSON.stringify( [ { id: attachment.id, url: attachment.url}]));
  });

  deleteButton.addEventListener( 'click', function(){
    img.removeAttribute( 'src' );
    hidden.removeAttribute( 'value' );
    img.removeAttribute( 'style' );
  });

  window.addEventListener( 'DOMContentLoaded', function(){
    img.setAttribute( 'src', imageUploads.imageData.src);
    img.setAttribute( 'style', 'width: 50%;');
    hidden.setAttribute('value', JSON.stringify( [imageUploads.imageData]));
  });
});

最佳答案

我实际上设法解决了这个问题。这是为我完成工作的JS。

    jQuery(document).ready(function(){
  var addButton = document.getElementById('last-opp-bilde');
  //var deleteButton = document.getElementById('fjern-bilde');
  var img = document.getElementById('image-tag');
  var hidden = document.getElementById('img-hidden-field');
  var imageUploader = wp.media({
    title: 'Velg bilde',
    button: {
      text: 'Velg bilde(r)'
    },
    multiple: 'add'
  });

  addButton.addEventListener( 'click', function() {
    if (imageUploader) {
      imageUploader.open();
    }
  });

  imageUploader.on('open',function() {
    var selection = imageUploader.state().get('selection');
    ids = jQuery('#img-hidden-field-selected').val().split(',');
      ids.forEach(function(id) {
    attachment = wp.media.attachment(id);
    attachment.fetch();
    selection.add( attachment ? [ attachment ] : [] );
  });
  });

  imageUploader.on( 'close', function() {
    //var attachment = imageUploader.state().get('selection').first().toJSON();
    var attachment = imageUploader.state().get('selection');
    var ids = attachment.map( function (attachment) {
        return attachment.id;
    });
    hidden.setAttribute( 'value', ids.join(',') );
  });

  imageUploader.on( 'select', function() {
    //var attachment = imageUploader.state().get('selection').first().toJSON();
    var attachment = imageUploader.state().get('selection');
    var ids = attachment.map( function (attachment) {
        return attachment.id;
    });
    hidden.setAttribute( 'value', ids.join(',') );
  });
});

09-16 16:40