This entry is part 5 of 5 in the Working with Widgets Series
- How to Create Advanced WordPress Widgets – @wproots
- Simple WordPress Widget Template
- Simple Recent Posts Widget
- List Categories Widget Plugin and Tutorial
- Adding the Farbtastic Color Picker to your WordPress Widgets
The Farbtastic Color Picker is a fantastic tool for developers and designers to utilize as a way to give their plugin (or theme) users an extra level of control. With Farbtastic, we can allow our users to change the colors of certain elements, such as the background color of our widget, by using an elegant color wheel. In this part of our Working With Widgets series, I’m going to show you how to add a color picker to your widget options panel.
For this tutorial, I’m not going to explain every piece of the widget, as by this point in the series, you should know how to create and save widget options 🙂 I’m just going to go through the parts related to the color picker. At the end, you can download the complete widget as a plugin.
Our Widget Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | /** * Sample color Picker Widget Class */ class sample_color_picker extends WP_Widget { /** constructor */ function sample_color_picker() { parent::WP_Widget(false, $name = 'Sample Color Picker Widget'); } /** @see WP_Widget::widget */ function widget($args, $instance) { extract( $args ); global $wpdb; $title = apply_filters('widget_title', $instance['title']); $background = $instance['background']; ?> <?php echo $before_widget; ?> <?php if ( $title ) echo $before_title . $title . $after_title; ?> <div style="background-color: <?php echo $background; ?>; height: 40px; width: 40px;">Sample</div> <?php echo $after_widget; ?> <?php } /** @see WP_Widget::update */ function update($new_instance, $old_instance) { $instance = $old_instance; $instance['title'] = strip_tags($new_instance['title']); $instance['background'] = strip_tags($new_instance['background']); return $instance; } /** @see WP_Widget::form */ function form($instance) { $title = esc_attr($instance['title']); $background = esc_attr($instance['background']); ?> <script type="text/javascript"> //<![CDATA[ jQuery(document).ready(function() { // colorpicker field jQuery('.cw-color-picker').each(function(){ var $this = jQuery(this), id = $this.attr('rel'); $this.farbtastic('#' + id); }); }); //]]> </script> <p> <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id('background'); ?>"><?php _e('Background Color:'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('background'); ?>" name="<?php echo $this->get_field_name('background'); ?>" type="text" value="<?php if($background) { echo $background; } else { echo '#fff'; // this is our default color } ?>" /> <div class="cw-color-picker" rel="<?php echo $this->get_field_id('background'); ?>"></div> </p> <?php } } // // register message box widget add_action('widgets_init', create_function('', 'return register_widget("sample_color_picker");')); function sample_load_color_picker_script() { wp_enqueue_script('farbtastic'); } function sample_load_color_picker_style() { wp_enqueue_style('farbtastic'); } add_action('admin_print_scripts-widgets.php', 'sample_load_color_picker_script'); add_action('admin_print_styles-widgets.php', 'sample_load_color_picker_style'); |
If you drop that into your functions.php, or your plugin file, you should have a fully functioning widget that has two fields: a title and a background input. Below the background input should be a color picker, like the image on the right.
There are a couple important parts to this widget (aside from the normal widget functions), so we’ll start with the first one.
In the form() function, we output a little bit of jQuery to activate our color picker on the appropriate input fields.
1 2 3 4 5 6 7 8 9 10 | jQuery(document).ready(function() { // colorpicker field jQuery('.cw-color-picker').each(function(){ var $this = jQuery(this), id = $this.attr('rel'); $this.farbtastic('#' + id); }); }); |
Notice that the class name in line 4 is the same as the class given to the DIV that we want to hold the color picker (just below the $background input field). Also notice that I have setup the id variable to contain the value of the rel attribute. This is how the color picker knows where to place the color code. The rel attribute has the same value of the id of $background input field. See below:
1 2 | <input class="widefat" id="<?php echo $this->get_field_id('background'); ?>" name="<?php echo $this->get_field_name('background'); ?>" type="text" value="<?php if($background) { echo $background; } else { echo '#fff'; } ?>" /> <div class="cw-color-picker" rel="<?php echo $this->get_field_id('background'); ?>"></div> |
Another important item to notice is that I have setup a conditional statement in the INPUT field’s value attribute. In order for the color picker to function completely, and for the widget to save the color option, the field MUST contain an initial color code value. If the field does not contain a default value, the background color of the field will change, but value attribute will NOT be updated, causing the color option to not save.
That’s it for the widget code itself, now we take a look at the functions that load the Farbtastic color picker script and style, which, conveniently, are included natively in WordPress. This makes them very, very easy to load.
1 2 3 4 5 6 | function sample_load_color_picker_script() { wp_enqueue_script('farbtastic'); } function sample_load_color_picker_style() { wp_enqueue_style('farbtastic'); } |
We have two functions: one for the farbtastic script, and one for the farbtastic CSS. Each of them is loaded the same way, using either wp_enqueue_script() or wp_enqueue_style(). After the functions, we tie into a couple of hooks to load the script/style onto our widgets page:
1 2 | add_action('admin_print_scripts-widgets.php', 'sample_load_color_picker_script'); add_action('admin_print_styles-widgets.php', 'sample_load_color_picker_style'); |
Notice the -widgets.php on the end of the hook names. By adding this suffix to the hook names, we ensure that the script and style only load on the widgets page, and not every other page in the WordPress admin.
And that’s it! Our widget is complete.
If you want, copy the whole code above, or download the complete widget as a plugin below.
Download
thanks for this..
been looking a dynamic way of adding the color poicker and up until now had to add it manually for each input.
this is great.
Glad I could help.
I have tried your sample widget and the farbtastic color picker will only work if you reload the page after adding the widget to a sidebar. I have attempted a few solutions but nothing seems to work. Does this happen for you as well in WordPress 3.2.1?
@c.bavota – I have had this problem before and have not yet found a way around it, though it is probably related to when the jQuery script is loaded.
Hi Pippin,
I haven’t gone through this tutorial just yet but have you figured a way to solve the issue c.bavota mentioned? I only ask because your tutorial is the only one I can find that mentions adding a color picker to a widget and it would fit perfectly for my theme. I sell my theme so I’d like to know it works without reloading the page before I add it to my theme 🙂
Just curious if anyone figured out the issue. If it’s when jQuery is loaded, any suggestions as to how to make it load quickly? Also, does WP already use farbtastic or another color picker jquery script that can simply be used without calling it for the widget? Not sure if I’m asking the right question but hopefully you know what I mean.
Cheers buddy
Scott
@scott – I have not come up with a solution yet, though it’s mostly because I’ve been focuses on other things. I imagine it has to do with when the scripts are loaded.
Fartastic is the one used and included in WordPress.
I’ve had the same problem, but I’ve found a solution that works (for me).
What we need to do is run the farbtastic script again when the ajax call of saving the widget is complete.
$j(document).ajaxSuccess(function(e, xhr, settings) {
var widget_id_base = ‘YOUR WIDGET BASE ID’;
if(settings.data.search(‘action=save-widget’) != -1 && settings.data.search(‘id_base=’ + widget_id_base) != -1) {
// Run the farbtastic code again
}
});
It did the job for me! Hope someone running into this post (just like I did) will find it useful!
This is where I found this information btw: http://www.johngadbois.com/adding-your-own-callbacks-to-wordpress-ajax-requests/
Greets, Sander
That’s great! Thanks so much for posting this!
Pingback: TutsPress | 20+ Helpful Free Wordpress Plugins Powered by Pippins
Tnx,,,,,I wa looking for that whole day .that make my task very easy,I was adding colorpicker in my plugin,,,But wordpress already has it ,,Tnx
Great job!
However I would like to choose the color in the front end instead
Could you help me? (I don’t know much about code yet)
Can you elaborate a little more and explain more fully what you want to do?
Pingback: Use the New WordPress 3.5 Color Picker in a Plugin | Rachel Baker
This is great but I think js color is better, easier to use and even more easier to implement in theme.
dear pippin,
I would like to use your widget but it´s not working on my page and I don´t know what I´m doing wrong.
The Iris is not showing after putting it into my right sidebar on my page.
Can you help me to make it work?
thanks so much!
greetings
Steffi
Thanks for sharing it i got it but have a one problem have any way to make it fold?when user want and click on it then its will be unfold
I mean color picker also unfold but i think its should be fold
Thanks