wp小工具添加自定义图片上传

Published
2022-11-16
浏览次数 :  218

首先要通过admin_enqueue_scripts钩子加载js文件, 首先要加载的是wp_enqueue_media

add_action('admin_enqueue_scripts', 'enqueue_widgets_script');
	# code...

function enqueue_widgets_script() {
	# code...
	wp_enqueue_media();
	wp_enqueue_script('widgetsjs', get_template_directory_uri() . '/js/widgets.js',false,'1.0.0.1',true);
}

然后在小工具class的代码里,添加后台代码, 首先是添加input的字段代码,然后是添加上传的按钮,按钮的id要和js的id相对应,实现打开和上传操作

<p>
        <label for="<?= $this->get_field_name( 'image_uri' ); ?>"><?php _e('Image', 'honghua')?></label>

        <img class="js_custom_upload_media_img" src="<?= (!empty($instance['image_uri'])) ? $instance['image_uri'] : ''; ?>" style="margin:0;padding:0;max-width:100%;display:block"/>

        <input type="text" id="<?php echo $this->get_field_id( 'image_uri' ); ?>" class="widefat js_custom_upload_media_url" name="<?= $this->get_field_name( 'image_uri' ); ?>" value="<?= ($instance['image_uri']) ? esc_attr($instance['image_uri']) : ''; ?>" style="margin-top:5px;" />
				
        <input type="button" id="js_custom_upload_media" class="button button-primary js_custom_upload_media" style="color:white" value="Upload Image" style="margin-top:5px;" />
    </p>

然后是Js文件的部分:

jQuery(document).ready(function ($) {
  function media_upload(button_selector) {
    var _custom_media = true,
      _orig_send_attachment = wp.media.editor.send.attachment;
    $('body').on('click', button_selector, function () {
      var button_id = $(this).attr('id');
      wp.media.editor.send.attachment = function (props, attachment) {
        if (_custom_media) {
          $('.' + button_id + '_img').attr('src', attachment.url);
          $('.' + button_id + '_url').val(attachment.url);
        } else {
          return _orig_send_attachment.apply($('#' + button_id), [props, attachment]);
        }
      }
      wp.media.editor.open($('#' + button_id));
      return false;
    });
  }
  media_upload('.js_custom_upload_media');
});

Top