2017-02-18 63 views
2

我有以下jQuery,它将打开wordpress媒体选择器,并将我选回的媒体文件的URL返回给我。在wordpress媒体选择器中获取多个图像

我设置了多个为true,所以我可以选择多个图像。

我的问题是如何获得第二张图片的网址。我似乎只能得到第一个。

奖金的问题 - 有没有办法将多重选择限制为只有2张图片?

jQuery(function($) { 
     $(document).ready(function(){ 
       $('#insert-my-media').click(open_media_window); 
      }); 

      function open_media_window() { 
       if (this.window === undefined) { 
        this.window = wp.media({ 
          title: 'Select a Before and After image', 
          library: {type: 'image'}, 
          multiple: true, 
          button: {text: 'Insert'} 
         }); 

        var self = this; // Needed to retrieve our variable in the anonymous function below 
        this.window.on('select', function() { 
          var first = self.window.state().get('selection').first().toJSON(); 
          wp.media.editor.insert('[banda before="' + first.url + ' after="' + second.url + '"]'); 
         }); 
       } 

       this.window.open(); 
       return false; 
      } 
    }); 

回答

0

要做到这一点,最好的方法是创建媒体编辑, 的2个实例,并使用“多:假”。

注意$(document).ready是没用的,因为通过使用语法jQuery(my_function)创建my_function是在文件准备好执行。

您可能需要像这样:

jQuery(function ($) { 
    var mediaPopup; 
    var placeholders = { 
     before: "@[email protected]", 
     after: "@[email protected]" 
    }; 
    var attrs = { 
     before: "before=", 
     after: "after=" 
    }; 
    var editorText = "[banda before='" + placeholders.before + 
     "' after='" + placeholders.after + "']"; 
    $("#choseBeforeMedia").on("click", function() { 
     openMediaPopup("before"); 
    }); 
    $("#choseAfterMedia").on("click", function() { 
     openMediaPopup("after"); 
    }); 

    var currentValues = { 
     before: function() { 
      var idx1 = editorText.indexOf(attrs.before) + attrs.before.length + 1; 
      var idx2 = editorText.indexOf(attrs.after) - 2; 
      return editorText.substring(idx1, idx2); 
     }, 
     after: function() { 
      var idx1 = editorText.indexOf(attrs.after) + attrs.after.length + 1; 
      var tmp = editorText.substring(idx1); 
      var idx2 = tmp.indexOf("'"); 
      return tmp.substring(0, idx2); 
     } 
    }; 

    function openMediaPopup(label) { 
     if (mediaPopup === undefined) { 
      mediaPopup = wp.media({ 
       title: "Select the " + label + " image", 
       library: {type: "image"}, 
       multiple: true, 
       button: {text: "Insert"} 
      }); 

      mediaPopup.on("select", function() { 
       var img = self.window.state().get("selection").toJSON(); 
       if (editorText.indexOf(placeholders[label]) > -1) { 
        editorText = editorText.replace(placeholders[label], img.url); 
       } 
       else { 
        editorText = editorText.replace(currentValues[label](), img.url); 
       } 
       wp.media.editor.insert(editorText); 
      }); 
     } 

     mediaPopup.open(); 

    } 
}); 
相关问题