扩展WP Customizer以实现多图像选择

时间:2017-05-02 作者:Tom Groot

Is there a way to extend the Wordpress Customizer, in order to enable multiple selections?

这看起来像我想要的:https://github.com/lucatume/multi-image-control. 我不能让它工作。它只显示add 按钮和remove 但他们什么都不做。

是否有其他现有的扩展脚本可以使用?

2 个回复
最合适的回答,由SO网友:Tom Groot 整理而成

我最终做的是extending the WP_Customize_Control 分类如下:

<?php

if (!class_exists(\'WP_Customize_Image_Control\')) {
    return null;
}

class Multi_Image_Custom_Control extends WP_Customize_Control
{
    public function enqueue()
    {
      wp_enqueue_style(\'multi-image-style\', get_template_directory_uri().\'/css/multi-image.css\');
      wp_enqueue_script(\'multi-image-script\', get_template_directory_uri().\'/js/multi-image.js\', array( \'jquery\' ), rand(), true);
    }

    public function render_content()
    { ?>
          <label>
            <span class=\'customize-control-title\'>Image</span>
          </label>
          <div>
            <ul class=\'images\'></ul>
          </div>
          <div class=\'actions\'>
            <a class="button-secondary upload">Add</a>
          </div>

          <input class="wp-editor-area" id="images-input" type="hidden" <?php $this->link(); ?>>
      <?php
    }
}
?>
当用户单击“添加”时,我使用javascript打开WP媒体选择器。选择图像时,图像必须显示在内部<ul class=\'images\'></ul>. 此外,用户需要能够通过单击图像来删除图像。我做了如下javascript file:

( function( $ ) {

        $(window).load(function(){
            var begin_attachment_string = $("#images-input").val();
            var begin_attachment_array = begin_attachment_string.split(",");
            for(var i = 0; i < begin_attachment_array.length; i++){
                if(begin_attachment_array[i] != ""){
                    $(".images").append( "<li class=\'image-list\'><img src=\'"+begin_attachment_array[i]+"\'></li>" );
                }
            }
            $(".button-secondary.upload").click(function(){
                var custom_uploader = wp.media.frames.file_frame = wp.media({
                    multiple: true
                });

                custom_uploader.on(\'select\', function() {
                    var selection = custom_uploader.state().get(\'selection\');
                    var attachments = [];
                    selection.map( function( attachment ) {
                        attachment = attachment.toJSON();
                        $(".images").append( "<li class=\'image-list\'><img src=\'"+attachment.url+"\'></li>" );
                        attachments.push(attachment.url);
                        //
                     });
                     var attachment_string = attachments.join() + "," + $(\'#images-input\').val();
                     $(\'#images-input\').val(attachment_string).trigger(\'change\');
                 });
                 custom_uploader.open();
             });

             $(".images").click(function(){
                 var img_src = $(event.target).find("img").attr(\'src\');
                 $(event.target).closest("li").remove();
                 var attachment_string = $(\'#images-input\').val();
                 attachment_string = attachment_string.replace(img_src+",", "");
                 $(\'#images-input\').val(attachment_string).trigger(\'change\');
             });
         });

} )( jQuery );
最后,我补充道some CSS:

.image-list{
  width: 100%;
  height: 150px;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  -webkit-box-shadow: inset 0 0 15px rgba(0,0,0,.1), inset 0 0 0 1px rgba(0,0,0,.05);
  box-shadow: inset 0 0 15px rgba(0,0,0,.1), inset 0 0 0 1px rgba(0,0,0,.05);
  background: #eee;
  cursor: pointer;
  vertical-align: middle;
  display:flex;
  justify-content:center;
  align-items:center;
  overflow: hidden;
  position: relative;
}
.image-list:before{
  content: \'\';
  position: absolute;
  display: none;
  top: 0px;
  right: 0px;
  left: 0px;
  bottom: 0px;
  box-shadow: inset 0 0 0 1px #fff, inset 0 0 0 5px #c60c31;
}
.image-list:hover:before{
  display: block;
}

SO网友:Ben Sevcik

@汤姆·格罗特这对我很管用,但我做了一些调整。这将保存ID而不是完整的url,删除后面的逗号,并避免使用;“事件”;因为它已经被弃用了。

Javascript:

  "use strict";
  $(window).load(function () {
    /*
    * Show photos on load
    */
    var begin_attachment_string = $("#images-input").val();
    var begin_attachment_array = begin_attachment_string.split(",");

    // get all attachments
    var promises = [];
    for (var i = 0; i < begin_attachment_array.length; i++) {
      var id = begin_attachment_array[i];
      if (id != "") {
        promises[i] = wp.media.attachment(id).fetch();
      }
    }
    // wait until they all finish since it\'s async
    Promise.all(promises)
    // add the images into the dom
    .then(function() {
      for (var i = 0; i < begin_attachment_array.length; i++) {
        var id = begin_attachment_array[i];
        if (begin_attachment_array[i] != "") {
          $(".images").append(
            "<li class=\'image-list\'><img src=\'" +
              wp.media.attachment(id).get("url") +
              "\' data-id=\'" +
              id +
              "\'></li>"
          );
        }
      }
    })


    /*
    * Add Photos
    */
    $(".button-secondary.upload").click(function () {
      var custom_uploader = (wp.media.frames.file_frame = wp.media({
        multiple: true,
      }));

      custom_uploader.on("select", function () {
        var selection = custom_uploader.state().get("selection");
        var attachments = [];
        selection.map(function (attachment) {
          attachment = attachment.toJSON();
          $(".images").append(
            "<li class=\'image-list\'><img src=\'" +
              attachment.url +
              "\' data-id=\'" +
              attachment.id +
              "\'></li>"
          );
          attachments.push(attachment.id);
        });
        var previous = $("#images-input").val() ? "," + $("#images-input").val() : ""; // get rid of trailing commas
        var attachment_string = attachments.join() + previous;
        $("#images-input").val(attachment_string).trigger("change");
      });
      custom_uploader.open();
    });


    /*
    * Remove images when you click on an image
    */
    $(".images").click(function (e) {
      var img_id = $(e.target).find("img").attr("data-id");
      $(e.target).closest("li").remove();
      var attachment_string = $("#images-input").val();
      attachment_string = attachment_string.replace(img_id, "");
      attachment_string = attachment_string.replaceAll(",,", ","); // get rid of duplicate commas
      attachment_string = attachment_string.replace(/^,+|,+$/g, ""); // get rid of leading or trailing commans
      $("#images-input").val(attachment_string).trigger("change");
    });
  });
})(jQuery);
php调用它:


function register_customize_sections( $wp_customize ) {
 
    $wp_customize->add_section( \'image_selector_section\', array(
       \'title\'=> __( \'Image Selector Section\', \'TextDomain\' ),
       \'priority\' => 201
    ) );

    $wp_customize->add_setting( 
        \'multi_image_selector\', 
        array(
            \'default\'   => array(),
            \'transport\' => \'refresh\',
        ) 
    );

    $wp_customize->add_control( new Multi_Image_Custom_Control (
        $wp_customize,
        \'multi_image_selector\',
        array(
            \'description\' => \'Select One or Multiple Images\',
            \'section\'  => \'image_selector_section\',
        )
    ) );
}
add_action(\'customize_register\', \'register_customize_sections\');```


相关推荐

Host images only on CDN

我开发了一个wordpress网站,该网站托管在AWS上。该网站运行良好,但由于我希望它成为一个电子商务网站,将有大量的图像。AWS的托管帐户仅提供30 GB的存储空间。所以我想host images completely on an external CDN off my server. 但最近对CDN的搜索导致我只缓存CDN,我希望只在其他服务器上托管图像。有线索吗?