How to add color picker to widgets?

I have some problems adding the wpColorPicker to a Widget. Does anyone have a working sample? It only works when I click on ‘Save’ or reload the page, but when I drag a new widget to the area it will not activate. Anyone any ideas? Below you can find my code so far.

class SampleWidget extends WP_Widget 
    {

        /**
         * Register widget with WordPress.
         */
        public function __construct () 
        {
            parent::__construct
            (
                'sample_widget',
                'Sample',
                array( 'description' => __( 'A sample description'), )
            );  

            add_action( 'admin_enqueue_scripts', array( &$this, 'admin_enqueue_scripts' ) );
        }

        public function admin_enqueue_scripts ( $hook_suffix )
        {
            if ( $hook_suffix != 'widgets.php' ) return;

            wp_enqueue_style( 'wp-color-picker' );          
            wp_enqueue_script( 'wp-color-picker' ); 
        }

        /**
         * Front-end display of widget.
         *
         * @see WP_Widget::widget()
         *
         * @param array $args     Widget arguments.
         * @param array $instance Saved values from database.
         */
        public function widget( $args, $instance ) 
        {
            extract( $args );

            echo $before_widget;
            echo $after_widget;
        }

        /**
         * Sanitize widget form values as they are saved.
         *
         * @see WP_Widget::update()
         *
         * @param array $new_instance Values just sent to be saved.
         * @param array $old_instance Previously saved values from database.
         *
         * @return array Updated safe values to be saved.
         */
        public function update( $new_instance, $old_instance ) 
        {
            $instance = array();
            return $instance;
        }

        /**
         * Back-end widget form.
         *
         * @see WP_Widget::form()
         *
         * @param array $instance Previously saved values from database.
         */
        public function form ( $instance ) 
        {
            ?>
            <p>  
                <label for="<?php echo $this->get_field_id( 'background-color' ); ?>">Achtergrondkleur:</label>
                <input type="text" id="<?php echo $this->get_field_id( 'background-color' ); ?>" name="<?php echo $this->get_field_name( 'background-color' ); ?>" value="<?php echo esc_attr( $backgroundColor ); ?>" />                              
            </p>

            <script type="text/javascript">
            jQuery(document).ready(function($){
                $('#<?php echo $this->get_field_id( 'background-color' ); ?>').wpColorPicker();
            });
            </script>
            <?php
        }
    }

Related posts

Leave a Reply

2 comments

  1. Here is the code I used for one of my projects:

    <?php
    function load_color_picker_style() {
        wp_enqueue_style( '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');
    ?>
    
    ///Javascript
    
    jQuery(document).ready(function($){
        function updateColorPickers(){
            $('#widgets-right .wp-color-picker').each(function(){
                $(this).wpColorPicker({
                    // you can declare a default color here,
                    // or in the data-default-color attribute on the input
                    defaultColor: false,
                    // a callback to fire whenever the color changes to a valid color
                    change: function(event, ui){},
                    // a callback to fire when the input is emptied or an invalid color
                    clear: function() {},
                    // hide the color picker controls on load
                    hide: true,
                    // show a group of common colors beneath the square
                    // or, supply an array of colors to customize further
                    palettes: ['#ffffff','#000000','#ff7c0b']
                });
            }); 
        }
        updateColorPickers();   
        $(document).ajaxSuccess(function(e, xhr, settings) {
    
            if(settings.data.search('action=save-widget') != -1 ) { 
                $('.color-field .wp-picker-container').remove();    
                updateColorPickers();       
            }
        });
     });
    

    The only requirement is that the input you want to be a colorpicker has to have the class name of, well, color-picker.

  2. I think what you really want to be doing is binding to the “sortstop” event which is triggered after a widget is dropped into a droppable sidebar area.

    jQuery('div.widgets-sortables').bind('sortstop', function(event,ui) {
        // This javascript code within here will be run after you've dropped a sidebar widget
    });
    

    This hasn’t been tested, but I reckon is probably the right avenue to pursue.