我在自定义小部件的开头卡住了:)当我单击应该用WP media uploader打开modal的按钮时,它不会打开它。我已经在函数和自定义JS加载中为小部件将JS排队,并且没有显示任何错误。我还尝试将这些按钮添加到简单的metabox中,它可以工作,但在小部件中没有结果。
Widget PHP
class Deo_Profile_Widget extends WP_Widget {
// setup the widget name, description etc.
function __construct() {
$widget_ops = array(
\'classname\' => "deo_profile_widget",
\'desciption\' => \'Custom Profile Widget\',
);
parent::__construct( \'deo_profile\', \'Deo Profile\', $widget_ops);
}
// update of the widget
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
return $instance;
}
// back-end display of widget
function form( $instance ) {
?>
<input type="hidden" id="image-hidden-field" name="custom_image_data">
<input type="button" id="image-upload-button" class="button button-primary" value="Add Image">
<input type="button" id="image-delete-button" class="button" value="Remove Image">
<?php
}
// front-end display of widget
function widget( $args, $instance ) {
echo "Hey";
}
}
add_action( \'widgets_init\', function() {
register_widget( \'Deo_Profile_Widget\' );
});
Widget JS
(function($){
/* WordPress Media Uploader
-------------------------------------------------------*/
var addButton = $(\'#image-upload-button\');
var deleteButton = $(\'#image-delete-button\');
var hiddenField = $(\'#image-hidden-field\');
var mediaUploader = wp.media.frames.file_frame = wp.media({
title: \'Select an Image\',
button: {
text: \'Use This Image\'
},
multiple: false
});
addButton.on(\'click\', function(e) {
e.preventDefault();
if ( mediaUploader ) {
mediaUploader.open();
return;
}
});
})(jQuery);
最合适的回答,由SO网友:Alexander 整理而成
经过数小时的测试和探索,我终于找到了导致问题的原因。如果我将类添加到按钮,它就会工作。但不是任何阶级,只有阶级deo-btn.
因此,这将起作用:
<input type="button" id="image-upload-button" class="deo-btn button button-primary" value="Add Image">
这不是:
<input type="button" id="image-upload-button" class="button button-primary" value="Add Image">
此外,这将不起作用:
<input type="button" id="image-upload-button" class="just-button button button-primary" value="Add Image">
真正奇怪的是,我仍然使用ID在JS中选择按钮
image-upload-button