Pippins Plugins
  • Email
  • Facebook
  • Feedburner
  • Github
  • Google
  • Twitter
  • Vimeo
  • Youtube
  • Rss
  • About
  • News
  • Join the Site
    • Member Benefits
    • Member Plugins
    • Email Notifications
  • Plugin Store
    • Affiliate Area
    • Checkout
  • Plugins
    • Plugin Portfolio
      • Plugin Portfolio – List View
    • Free
    • Premium
    • Member Plugins
    • Coding Standards
    • Get Plugin Support
  • Tutorials
    • Series
      • Plugin Development 101
      • Creating a User Follow System Plugin
      • Customizing Restrict Content Pro
      • Displaying Content with Easy Content Types
      • Writing Your First WordPress Plugins, Basic to Advanced
      • Working with Widgets
      • User Submitted Image Galleries
      • Plugin Thoughts
      • Integrating Stripe.com with WordPress
      • WordPress Rewrite API
    • Member Exclusive
      • Free Members
      • Subscriber Only
    • Difficulty
      • Beginner
      • Intermediate
      • Advanced
    • Action and Filter Hooks
    • Ajax
    • Custom Post Types
    • External APIs
    • Short Codes
    • Taxonomies
    • Video Tutorials
    • Widget Tutorials
    • WordPress Admin / Dashboard
    • Working with jQuery
    • WordPress Database
    • Writing Plugins
    • Tag Index
  • Reviews
  • Support Forum
  • Contact
    • Support the Site
    • Request Code Review
    • Plugin Support

Adding the Farbtastic Color Picker to your WordPress Widgets

Posted on July 22, 2011 by Pippin in Intermediate, Tutorials, Widget Tutorials, Working with jQuery, Writing Plugins 14 Comments
Home» Tutorials » Intermediate » Adding the Farbtastic Color Picker to your WordPress Widgets
Tweet
Love It - 2
This entry is part 5 of 5 in the Working with Widgets Series
← List Categories Widget Plugin and Tutorial
  • 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
Tweet Follow @pippinsplugins
color picker, farbtastic, jquery, widget, widgets

14 comments on “Adding the Farbtastic Color Picker to your WordPress Widgets”

  1. Lee Mason says:
    September 17, 2011 at 3:50 pm

    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.

    Reply
    • Pippin says:
      September 17, 2011 at 4:17 pm

      Glad I could help.

  2. c.bavota says:
    September 19, 2011 at 3:06 pm

    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?

    Reply
    • Pippin says:
      September 19, 2011 at 3:08 pm

      @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.

  3. Scott says:
    October 19, 2011 at 6:53 pm

    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

    Reply
    • Pippin says:
      October 19, 2011 at 11:38 pm

      @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.

    • Sander says:
      January 15, 2012 at 4:50 am

      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

    • Pippin says:
      January 15, 2012 at 10:19 am

      That’s great! Thanks so much for posting this!

  4. TutsPress | 20+ Helpful Free Wordpress Plugins Powered by Pippins says:
    January 29, 2012 at 1:59 pm

    [...] You can add a color picker with this plugin on your blogs. Click download link for more information, demo and full tutorial. Download now → [...]

    Reply
  5. Ramandeep singh says:
    July 17, 2012 at 7:51 am

    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

    Reply
  6. David Cibin says:
    November 24, 2012 at 12:50 pm

    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)

    Reply
    • Pippin says:
      November 24, 2012 at 3:53 pm

      Can you elaborate a little more and explain more fully what you want to do?

  7. Use the New WordPress 3.5 Color Picker in a Plugin | Rachel Baker says:
    November 27, 2012 at 5:47 pm

    [...] As soon as I saw Iris, I fell in love. She is user-friendly, colorful and fun. I found that implementing the new color picker is very similar to Farbtastic. [...]

    Reply
  8. sayed taqui says:
    May 5, 2013 at 1:49 pm

    This is great but I think js color is better, easier to use and even more easier to implement in theme.

    Reply

Leave a Reply Cancel reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Login

Lost your password?

Please enter your username or e-mail address. You will receive a new password via e-mail.

  • Facebook Become a Fan Like

  • Twitter Subscribe on Twitter Follow

  • YouTube Follow my Videos Subscribe

  • RSS Feed Subscribe with RSS Subscribe

Easy Digital Downloads

Most Loved

  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages
  • Simple Notices Pro Plugin for WordPress
  • User Bookmarks for WordPress
  • Front End Registration and Login Forms Plugin

Similar Plugins and Posts

  • Use wp_localize_script, It Is Awesome
  • Create a Live Search in WordPress with jQuery and Ajax
  • Loading Scripts Correctly in the WordPress Admin
  • Review: Cudazi Scroll to Top
  • Full Screen Background Images Plugin

Latest Premium Content

  • Plugin Development 101 – Introduction to Adding Dashboard Menus
  • Plugin Development 101 – Intro to Loading Scripts and Styles
  • User Follow System – Part 5
  • Plugin Development 101 – Intro to Short Codes

Latest Tutorials

  • Storing Session Data in WordPress without $_SESSION (19)

    The term Session in web development refers to...

  • Test Your Plugins with RTL (1)

    Right-To-Left languages are those that...

  • Submitting Your First Pull Request to a WordPress Plugin on Github (5)

    Github is an extremely popular tool for managing WordPress plugins, and one...

Enter your email to receive automated updates when new posts are published

WP Core Contributions

  • [24316]

View the ticket on Trac.

WP Codex Contributions

  • Function: shortcode exists
  • Function: has shortcode
  • Function: shortcode exists
  • Function: shortcode exists
  • Function: has shortcode

View all 41 changes in the Codex.

Latest Tweets

  • Could not fetch Twitter RSS feed.

Topics

contextual help featured register_setting shortcodes attachments add_options_page Tom McFarlin get_user_meta hook add_shortcode meta box Sugar Event Calendar wp_enqueue_script forms short codes plugin do_action login Related posts authors mail chimp attachment image recent posts post types apply_filters comments short code bbpress taxonomies custom post type Ajax gallery images Stripe taxonomy jquery widgets users add_filter easy content types add_action widget restrict content pro easy digital downloads

Weekly Newsletter

Useful Links

  • Join the Site
  • Plugin Store
  • Affiliate Area
  • Tag Index
  • Support the Site
  • Suggest a Tutorial
  • Random Post
  • Contact

Monthly Archives

(c) 2013 Pippin's Plugins