wp.media
是WordPress用于显示媒体库模式的JavaScript API。
您可以通过将自定义JS脚本排入管理页面的队列来使用它:
wp_enqueue_script(\'media-upload\');
wp_enqueue_media();
wp_enqueue_script(
\'pb-admin-script\',
\'admin.js\',
array(
\'jquery\',
)
);
然后像这样使用它:
HTML:
<button class="upload_image_button button button-primary">
<?php _e(\'Upload Image\', \'pb\'); ?>
</button>
<img src="" id="image-preview" style="display: none"/>
JS公司:
jQuery(document).ready(function($) {
$(document).on(\'click\', \'.upload_image_button\', function(event) {
event.preventDefault();
var imgPrev = $(\'#image-preview\');
var file_frame = wp.media.frames.file_frame = wp.media({
title: \'Select or upload image\',
library: {
type: \'image\'
},
button: {
text: \'Select\'
},
multiple: false,
});
file_frame.on(\'select\', function() {
var attachment = file_frame.state().get(\'selection\').first().toJSON();
imgPrev.src = attachment.url;
imgPrev.style.removeProperty(\'display\');
});
file_frame.open();
});
});