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
}
}
Here is the code I used for one of my projects:
The only requirement is that the input you want to be a colorpicker has to have the class name of, well,
color-picker
.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.
This hasn’t been tested, but I reckon is probably the right avenue to pursue.