我用AJAX
.
下面是解决方案。
HTML:
<label><?php _e( \'Featured Image\', EG360_TEXT_DOMAIN ); ?></label>
<div id="eg360_tax_image" style="float: left; margin-right: 10px;">
<img src="<?php echo esc_url( eg360_placeholder_image() ); ?>" width="60px" height="60px"/>
</div>
<div style="line-height: 60px;">
<input type="hidden" id="eg360_tax_image_id" name="eg360_tax_image_id"/>
<button type="button" class="upload_image_button button"><?php _e( \'Upload/Add image\', EG360_TEXT_DOMAIN ); ?></button>
<button type="button" class="remove_image_button button"><?php _e( \'Remove image\', EG360_TEXT_DOMAIN ); ?></button>
</div>
jQuery:
jQuery(document).ready(function ($) {
if (!$(\'#product_cat_thumbnail_id\').val()) {
$(\'.remove_image_button\').hide();
}
var file_frame;
$(\'body\').on(\'click\', \'.upload_image_button\', function (event) {
event.preventDefault();
if (file_frame) {
file_frame.open();
return;
}
file_frame = wp.media.frames.downloadable_file = wp.media({
title: \'<?php _e( \'Choose a Fetured Image\', EG360_TEXT_DOMAIN ); ?>\',
button: {
text: \'<?php _e( \'Use as Fetured Image\', EG360_TEXT_DOMAIN ); ?>\'
},
multiple: false
});
file_frame.on(\'select\', function () {
var attachment = file_frame.state().get(\'selection\').first().toJSON();
var attachment_thumbnail = attachment.sizes.thumbnail || attachment.sizes.full;
$(\'#eg360_tax_image_id\').val(attachment.id);
$(\'#eg360_tax_image\').find(\'img\').attr(\'src\', attachment_thumbnail.url);
$(\'.remove_image_button\').show();
$(\'.upload_image_button\').hide();
});
file_frame.open();
});
$(\'body\').on(\'click\', \'.remove_image_button\', function () {
$(\'#eg360_tax_image\').find(\'img\').attr(\'src\', \'<?php echo esc_js( eg360_placeholder_image() ); ?>\');
$(\'#eg360_tax_image_id\').val(\'\');
$(\'.remove_image_button\').hide();
$(\'.upload_image_button\').show();
return false;
});
$(\'body\').ajaxComplete(function (event, request, options) {
if (request && 4 === request.readyState && 200 === request.status
&& options.data && 0 <= options.data.indexOf(\'action=add-tag\')) {
var res = wpAjax.parseAjaxResponse(request.responseXML, \'ajax-response\');
if (!res || res.errors) {
return;
}
$(\'#eg360_tax_image\').find(\'img\').attr(\'src\', \'<?php echo esc_js( eg360_placeholder_image() ); ?>\');
$(\'#eg360_tax_image_id\').val(\'\');
return;
}
});
});