【问题标题】:Wordpress custom meta box multiple image uploadWordpress 自定义元框多张图片上传
【发布时间】:2016-08-25 23:08:07
【问题描述】:

我正在使用添加了自定义元框的自定义帖子类型。在自定义元框中,我正在尝试为多个图像添加媒体上传器。使用这个上传器,我想将多个图像 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]));
  });
});

【问题讨论】:

    标签: javascript php jquery wordpress


    【解决方案1】:

    我实际上设法解决了这个问题。这是为我完成这项工作的 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(',') );
      });
    });
    

    【讨论】:

      【解决方案2】:

      将以下代码添加到您当前的主题 function.php 文件中。从 WordPress 管理员转到您的页面,并检查是否将多个图像上传自定义字段添加到每个页面。

      <?php
      // Add Meta Box to post
      add_action( 'add_meta_boxes', 'multi_media_uploader_meta_box' );
      
      function multi_media_uploader_meta_box() {
          add_meta_box( 'my-post-box', 'Media Field', 'multi_media_uploader_meta_box_func', 'post', 'normal', 'high' );
      }
      
      function multi_media_uploader_meta_box_func($post) {
          $banner_img = get_post_meta($post->ID,'post_banner_img',true);
          ?>
          <style type="text/css">
              .multi-upload-medias ul li .delete-img { position: absolute; right: 3px; top: 2px; background: aliceblue; border-radius: 50%; cursor: pointer; font-size: 14px; line-height: 20px; color: red; }
              .multi-upload-medias ul li { width: 120px; display: inline-block; vertical-align: middle; margin: 5px; position: relative; }
              .multi-upload-medias ul li img { width: 100%; }
          </style>
      
          <table cellspacing="10" cellpadding="10">
              <tr>
                  <td>Banner Image</td>
                  <td>
                      <?php echo multi_media_uploader_field( 'post_banner_img', $banner_img ); ?>
                  </td>
              </tr>
          </table>
      
          <script type="text/javascript">
              jQuery(function($) {
      
                  $('body').on('click', '.wc_multi_upload_image_button', function(e) {
                      e.preventDefault();
      
                      var button = $(this),
                      custom_uploader = wp.media({
                          title: 'Insert image',
                          button: { text: 'Use this image' },
                          multiple: true 
                      }).on('select', function() {
                          var attech_ids = '';
                          attachments
                          var attachments = custom_uploader.state().get('selection'),
                          attachment_ids = new Array(),
                          i = 0;
                          attachments.each(function(attachment) {
                              attachment_ids[i] = attachment['id'];
                              attech_ids += ',' + attachment['id'];
                              if (attachment.attributes.type == 'image') {
                                  $(button).siblings('ul').append('<li data-attechment-id="' + attachment['id'] + '"><a href="' + attachment.attributes.url + '" target="_blank"><img class="true_pre_image" src="' + attachment.attributes.url + '" /></a><i class=" dashicons dashicons-no delete-img"></i></li>');
                              } else {
                                  $(button).siblings('ul').append('<li data-attechment-id="' + attachment['id'] + '"><a href="' + attachment.attributes.url + '" target="_blank"><img class="true_pre_image" src="' + attachment.attributes.icon + '" /></a><i class=" dashicons dashicons-no delete-img"></i></li>');
                              }
      
                              i++;
                          });
      
                          var ids = $(button).siblings('.attechments-ids').attr('value');
                          if (ids) {
                              var ids = ids + attech_ids;
                              $(button).siblings('.attechments-ids').attr('value', ids);
                          } else {
                              $(button).siblings('.attechments-ids').attr('value', attachment_ids);
                          }
                          $(button).siblings('.wc_multi_remove_image_button').show();
                      })
                      .open();
                  });
      
                  $('body').on('click', '.wc_multi_remove_image_button', function() {
                      $(this).hide().prev().val('').prev().addClass('button').html('Add Media');
                      $(this).parent().find('ul').empty();
                      return false;
                  });
      
              });
      
              jQuery(document).ready(function() {
                  jQuery(document).on('click', '.multi-upload-medias ul li i.delete-img', function() {
                      var ids = [];
                      var this_c = jQuery(this);
                      jQuery(this).parent().remove();
                      jQuery('.multi-upload-medias ul li').each(function() {
                          ids.push(jQuery(this).attr('data-attechment-id'));
                      });
                      jQuery('.multi-upload-medias').find('input[type="hidden"]').attr('value', ids);
                  });
              })
          </script>
      
          <?php
      }
      
      
      function multi_media_uploader_field($name, $value = '') {
          $image = '">Add Media';
          $image_str = '';
          $image_size = 'full';
          $display = 'none';
          $value = explode(',', $value);
      
          if (!empty($value)) {
              foreach ($value as $values) {
                  if ($image_attributes = wp_get_attachment_image_src($values, $image_size)) {
                      $image_str .= '<li data-attechment-id=' . $values . '><a href="' . $image_attributes[0] . '" target="_blank"><img src="' . $image_attributes[0] . '" /></a><i class="dashicons dashicons-no delete-img"></i></li>';
                  }
              }
      
          }
      
          if($image_str){
              $display = 'inline-block';
          }
      
          return '<div class="multi-upload-medias"><ul>' . $image_str . '</ul><a href="#" class="wc_multi_upload_image_button button' . $image . '</a><input type="hidden" class="attechments-ids ' . $name . '" name="' . $name . '" id="' . $name . '" value="' . esc_attr(implode(',', $value)) . '" /><a href="#" class="wc_multi_remove_image_button button" style="display:inline-block;display:' . $display . '">Remove media</a></div>';
      }
      
      // Save Meta Box values.
      add_action( 'save_post', 'wc_meta_box_save' );
      
      function wc_meta_box_save( $post_id ) {
          if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
              return; 
          }
      
          if( !current_user_can( 'edit_post' ) ){
              return; 
          }
          
          if( isset( $_POST['post_banner_img'] ) ){
              update_post_meta( $post_id, 'post_banner_img', $_POST['post_banner_img'] );
          }
      }?>
      

      使用下面的代码从任何地方显示元框值

      <?php
      // Use below code to show metabox values from anywhere
      $id = get_the_ID();
          $banner_img = get_post_meta($id, 'post_banner_img', true);  
          $banner_img = explode(',', $banner_img);
          if(!empty($banner_img)) {
              ?>
              <table class="plugin-detail-tabl" width="100%" cellspacing="0" cellpadding="0">
                  <tbody>
                      <?php  foreach ($banner_img as $attachment_id) { ?>
                          <tr>
                              <td><img src="<?php echo wp_get_attachment_url( $attachment_id );?>"></td>
                          </tr>
                      <?php } ?>
                  </tbody>
              </table>
              <?php
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-18
        • 1970-01-01
        • 2011-06-27
        • 2018-08-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多