Wordpress - 使用媒体库获取图像

时间:2015-10-01 16:24:01

标签: php ajax wordpress image forms

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

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

如果可能,我怎么能用AJAX做到这一点?

2 个答案:

答案 0 :(得分:8)

首先,您需要将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');

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

<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 输入现在将包含该网址,并将保存在表单提交中。

答案 1 :(得分:0)

用例是:我有一个包含 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>