【问题标题】:Wordpress - Get an image using the media libraryWordpress - 使用媒体库获取图像
【发布时间】:2015-12-29 19:01:49
【问题描述】:

我正在创建一个插件,我有一个管理页面

在该页面的选项中,我想添加一个按钮,允许我打开 Wordpress 媒体库并从中选择一个图像,然后获取所选图像的 URL 和 alt 属性。

如果可能的话,我如何使用 AJAX 做到这一点?

【问题讨论】:

    标签: php ajax wordpress image forms


    【解决方案1】:

    首先,您需要将 wordpress 核心媒体脚本和自定义 js 脚本加入队列

    function my_enqueue_media_lib_uploader() {
    
        //Core media script
        wp_enqueue_media();
    
        // Your custom js file
        wp_register_script( 'media-lib-uploader-js', plugins_url( 'media-lib-uploader.js' , __FILE__ ), array('jquery') );
        wp_enqueue_script( 'media-lib-uploader-js' );
    }
    add_action('admin_enqueue_scripts', 'my_enqueue_media_lib_uploader');
    

    然后假设您在选项页面中有这个标记:一个上传按钮和一个用于存储所选图像 url 的文本输入

    <form method="post">
        <input id="image-url" type="text" name="image" />
        <input id="upload-button" type="button" class="button" value="Upload Image" />
        <input type="submit" value="Submit" />
    </form>
    

    您需要添加此 javascript 代码来调用上传器弹出窗口

    jQuery(document).ready(function($){
    
      var mediaUploader;
    
      $('#upload-button').click(function(e) {
        e.preventDefault();
        // If the uploader object has already been created, reopen the dialog
          if (mediaUploader) {
          mediaUploader.open();
          return;
        }
        // Extend the wp.media object
        mediaUploader = wp.media.frames.file_frame = wp.media({
          title: 'Choose Image',
          button: {
          text: 'Choose Image'
        }, multiple: false });
    
        // When a file is selected, grab the URL and set it as the text field's value
        mediaUploader.on('select', function() {
          attachment = mediaUploader.state().get('selection').first().toJSON();
          $('#image-url').val(attachment.url);
        });
        // Open the uploader dialog
        mediaUploader.open();
      });
    
    });
    

    选择图像后,您的 image-url 输入现在将包含该 url,并将保存在表单提交中。

    【讨论】:

      【解决方案2】:

      用例是:我有一个包含 index.php 作为主文件的插件,我希望能够单击一个按钮并打开媒体库并从中选择一个图像,这个图像应该加载到一个图像中标记。

      1- 将脚本添加到您的主 PHP 插件

      // index.php
      
      // ...
      
      // add script js for page
      add_action('admin_enqueue_scripts', function () {
          // Enqueue WordPress media scripts
          if ($_GET["page"]== 'debug_area') {
              wp_enqueue_media();
              // Enqueue custom script that will interact with wp.media
              wp_enqueue_script(
                  'myprefix_script',
                  plugins_url('/load_img.js', __FILE__),
                  array('jquery'),
                  '0.1');
          }
      });
      
      // add ajax action to get the image async
      add_action('wp_ajax_get_image_from_media_lib', function () {
          if (isset($_GET['id'])) {
              $image = wp_get_attachment_image(
                  filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT),
                  'medium',
                  false,
                  array('id' => 'image_preview')
              );
              $data = array(
                  'image' => $image,
              );
              wp_send_json_success($data);
          } else {
              wp_send_json_error();
          }
      });
      

      2-添加已经包含在enqueue中的文件JS

      // load_img.js
      jQuery(document).ready(_ => {
          console.clear();
      
          /**
           * Define media_lib_frame as wp.media object
           */
          const media_lib_frame = wp.media({
              title: 'Select Media',
              multiple: false,
              library: {
                  type: 'image',
              }
          });
      
          /**
           * On close, get selections and save to the hidden input
           * plus other AJAX stuff to refresh the image preview
           */
          media_lib_frame.on('close', _ => {
              const selection = media_lib_frame.state().get('selection');
              const gallery_ids = selection.map(attachment => attachment['id']);
              const ids = gallery_ids.join(",");
              jQuery('input#idImage').val(ids);
              loadImage(ids);
          });
      
          /**
           * On open, get the id from the hidden input
           * and select the appropriate images in the media manager
           */
          media_lib_frame.on('open', _ => {
              const selection = media_lib_frame.state().get('selection');
              const ids = jQuery('input#idImage').val().split(',');
              ids.forEach(id => {
                  const attachment = wp.media.attachment(id);
                  attachment.fetch();
                  selection.add(attachment ? [attachment] : []);
              });
          });
      
          jQuery('button#btnOpenMediaLibFrame').click(e => {
              e.preventDefault();
              media_lib_frame.open();
          });
      });
      
      // Ajax request to refresh the image preview
      const loadImage = the_id => {
          const data = {action: 'get_image_from_media_lib', id: the_id};
      
          jQuery.get(ajaxurl, data, response => {
              if (response.success === true) {
                  jQuery('#image_preview').replaceWith(response.data.image);
              }
          });
      }
      

      3-将此HTML添加到负责渲染视图的函数中

      <img id="image_preview"/>
      <input
          type="hidden"
          id="idImage"
          class="regular-text"/>
      <button
          type='button'
          class="button-primary"
          id="btnOpenMediaLibFrame">
          Select a image
      </button>
      

      【讨论】:

        猜你喜欢
        • 2014-01-06
        • 1970-01-01
        • 2015-04-22
        • 2015-05-07
        • 2015-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多