Adding WordPress colorpicker in widget settings

enter image description here

I want to add the WordPress default colorpicker in widget settings form. Here’s what I’m trying:

In my functions.php, I have this:

function widgets_scripts( $hook ) {
    if ( 'widgets.php' != $hook ) {
    wp_enqueue_style( 'wp-color-picker' );        
    wp_enqueue_script( 'wp-color-picker' ); 
add_action( 'admin_enqueue_scripts', 'widgets_scripts' );

In my widget file, I have this:

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $('#<?php echo $this->get_field_id( 'color' ); ?>').wpColorPicker();
<input id="<?php echo $this->get_field_id( 'color' ); ?>" type="text" name="<?php echo $this->get_field_name( 'color' ); ?>" value="<?php echo esc_attr( $instance['color'] ); ?>" />

Using the above code, I can see the colorpicker “Select color” button, but it does not let me click it initially.

It only lets me click after the widget is saved. I’m guessing that it is because of assigning the ID.

If I try to use a css class name, it displays the button 2 times (I don’t know why, even the class exists only once in a widget). This is what I see if I use class name:

Also i think class name will cause the problem if same widget is used multiple times. That’s why I’m trying to use a dynamic ID for the input field.

Read more here: Adding WordPress colorpicker in widget settings

Leave a Reply

Your email address will not be published. Required fields are marked *