I'm trying to create a plugin that is basically just a WordPress widget. I'm having great difficulty getting the WordPress color picker to function correctly when my widget is first added to the sidebar. I've followed these instructions for integrating the picker. However, this causes two color pickers to show in the sidebar when the widget is first added, only one of which is functional. Once the settings are saved, the second color picker is removed and everything works as expected.
I've also tried adding the color picker after the ajaxComplete
event fires instead of ready
, but that produces the same result - two color pickers.
I then uncovered this WordPress bug that has been marked as being invalid. When I tried the recommended approach of using the sortstop
event, I had even worse results - duplicate color pickers, none of which actually functioned.
I'm looking for solutions to this problem as I've reached a dead-end and can't release this plugin with a known bug. Is there perhaps a way to force a save when the widget is first added? Or is there some other way that I haven't considered in which to address this problem?
Thx!
Update - Here's the relevant code related to the color picker:
function load_color_picker_style() {
wp_enqueue_style('wp-color-picker');
}
function load_color_picker_script() {
wp_enqueue_script('wp-color-picker');
}
add_action('admin_print_scripts-widgets.php', 'load_color_picker_script');
add_action('admin_print_styles-widgets.php', 'load_color_picker_style');
function form( $instance ) {
$defaults = array(
'text_color' => '#000',
);
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
<script>
//This shows two color pickers. So does using ajaxComplete or sortstop.
jQuery(document).ready(function($) {
$('.color-picker').wpColorPicker();
});
</script>
<p>
<label for="<?php echo $this->get_field_id( 'text_color' ); ?>"><?php _e( 'Text Color', 'date-time' ) ?>:</label>
<input id="<?php echo $this->get_field_id( 'text_color' ); ?>" name="<?php echo $this->get_field_name( 'text_color' ); ?>" type="text" value="<?php echo esc_attr( $instance[ 'text_color' ] ); ?>" class="color-picker" />
</p>
<?php
}