How to add a color picker in your wp theme using frabtastic

by krike in General on 22 Jul 2011


Previously I wrote a tutorial on how to add a color picker to your admin theme page. I therefore choose a specific library which I used to create these color pickers. That was before I actually found that wordpress already includes a javascript library to create color pickers. In this quick tutorial I will teach you how to use it.

You can download the result of this tutorial as a twentyten child theme

A brief word about wp_enqueue_script()

I actually found this when looking at the wp_enqueue_script(); in the wordpress codex. When I scrolled down I saw an entire list of javascript libraries that are already present in wordpress, which you could then easily load using the wp_enqueue_script();. I strongly advice you have a look at all the libraries you can include. And who knows, just like me, you might find out you are including a javascript or jQuery library that is already present in wordpress.

Before getting started

Before we start let’s add a simple link into the theme menu block in the admin area which links to a page which will contain the color picker. Just add the following code in the functions.php of your theme:

add_action('admin_menu', 'themeoptions_admin_menu'); //action to display the menu
function themeoptions_admin_menu()
{
add_theme_page('color picker', 'color picker', 'read', 'color_picker_option', 'color_picker_option_page');
}
function color_picker_option_page()
{

}

color_picker_option_page() is the function we specified to show the color pickers.

Add the color picker

First of all we need to load the farbtastic javascript library and style. Add the following code to your functions.php of your theme:

add_action('init', 'load_theme_scripts');
function load_theme_scripts() {
    wp_enqueue_style( 'farbtastic' );
    wp_enqueue_script( 'farbtastic' );
}

We then add a simple form in our color_picker_option_page() function:

<form method="POST" action="">
     <input type="text" id="color1" value="<?php echo get_option('color1'); ?>" name="color_picker_color1" />
     <div id="color_picker_color1"></div>
     <p><input type="submit" name="update_options" value="Update Options" /></p>
</form>

Now all that remains is to call the frabtastic function and specify where the color picker should be loaded and which input field will be used to dynamicly update the color value once you select another color. Add the following code in the color_picker_option_page() :

<script type="text/javascript">
        jQuery(document).ready(function($){
            $('#color_picker_color1').farbtastic('#color1');            
        });
    </script>

You should now have a working color picker:

Saving the color

The last thing to do is to store the color value in a wordpress option. At the top of the color_picker_option_page() function add:

if ( isset($_POST['update_options'])) { color_picker_option_update(); }

So when the form is submitted the color_picker_option_update() function will be called. So let’s create that function and save the color value:

function color_picker_option_update()
{
update_option('color1', esc_html($_POST['color_picker_color1']));
}

So we get the color value using $_POST and we filter it using esc_html() (always filter submitted data!!) and finally it is saved. Update_option() will create the new option if it doesn’t exist yet.

Adding a second color picker

First of all copy/paste a second row for the second color picker

<tr valign="top">
	<th width="200px" scope="row">Color 2</th>
	<td>	
		<input type="text" id="color2" value="<?php echo get_option('color2'); ?>" name="color_picker_color2" />
		<div id="color_picker_color2"></div>
	</td>
</tr>

Add a second call to the farbtastic plugin

$('#color_picker_color2').farbtastic('#color2');

Finally save the new color picker value in the update functions using the update_option() function

update_option('color2', esc_html($_POST['color_picker_color2']));

The see the final code download the twentyeleven child theme at the top of this article.

That’s it!

So that’s all there is to do. Pretty easy, no? Much easier and faster than using jPicker which I introduced in my previous tutorial.

Written by krike

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam sit amet nisl nisl. Ut interdum libero vitae quam ultricies et lacinia elit aliquet. Praesent tincidunt, sem tempus feugiat feugiat, turpis tellus scelerisque erat, sit amet feugiat neque arcu ac lectus. Sed at mi et elit interdum scelerisque vitae eu felis.

krike has written 77 posts.

  • webcloudstudios

    Hello

    Thanks for the cool script!

    please fix the code here :

    function color_picker_option_update()
    {
    update_option(‘color1’, esc_html($_POST[‘color1’]));
    }

    make it

    function color_picker_option_update()
    {
    update_option(‘color1’, esc_html($_POST[‘color_picker_color1’]));
    }

    • @webcloudstudios: thanks for pointing that out

  • Guus

    Hi Christophe,
    Thanks for the script and the clear explanation. Without any PHP knowledge I was able to get the colorpicker up and running in the WordPress adminpanel.
    However (and that is probably my lack of PHP knowledge) I don’t know how to add the chosen color to my layout. So when I pick a color, how can I add that to a certain div in my CSS file?
    I hope you can help me out with this or send me in the right direction.

    • @Guus: You are welcome and it is actually not that difficult.You just need to call the get_option() function provided by wordpress and just print it out. For example create a style block:

      <style type="text/css">
      div.myDiv{
      background-color: <?php echo get_option('color1'); ?>;
      }
      </style>

      You can obviously not use that in a css file itself.

  • Guus

    Thanks again, after some tries I have it working now!

  • Thanks for this!
    I would like to give users the possibility to change more than one color.
    color1, color2, color3 and so on.
    How can i manage that?

  • Ankit

    <input type="text" id="color1" value="" name="color_picker_color1" />

    <input type="text" id="color2" value="" name="color_picker_color2" />

    jQuery(document).ready(function($){
    $('#color_picker_color1').farbtastic('#color1');
    $('#color_picker_color2').farbtastic('#color2');

    }

    function color_picker_option_update()
    {
    update_option('color1', esc_html($_POST['color_picker_color1']));
    update_option('color2', esc_html($_POST['color_picker_color2']));
    }

    i am trying to use this code for multiple color pickers on same page,it is working well but with one issue that when we select colors for these two only first one shows hexadecimal code for color chosen

    Second one only shows color chosen not hexadecimal

    Help me please…

    • @Ankit: I will update this tutorial today by including some code (tested of course) on how to add multiple color pickers.

  • Ankit

    Thanks @krike …i’ll be Eagerly waiting 🙂

  • Matti

    I have been trying to get this to work for some time, but I jsut can’t get this to save the color. I have added the css to my header, I have added the script – can pick a color, but it doesn’t save it. What am i doing wrong???

    • @matti: did you downloaded the child theme? (see link in the notification box at the top) compare it with your code.

  • Matti

    I pasted the functions file directly into the theme, and added:
    body{
    background-color: ;
    }

    To my header. The color picker is showing but no color saves.

    • @matti: could you send your theme in a zip to krike06 [at] gmail [dot] com. That way i can see what’s wrong

  • I updated the tutorial to include a second color picker. I also updated the twentyeleven child theme. There was a small bug in there as well which I fixed.

  • Ankit

    @krike…Thanks code works perfect…now i’ll try with advanced color picker..please Add full tutorial package also there like this so its been easy for everyone..:)

  • Felix

    Just had a question about how to add a reset button. When clicked I would like it go back to just a standard # in the fields.

    • @Felix: Create a link or button and give it an id of reset-colors. Then you should check when the button/link was clicked in jQuery and update the value of the input fields:
      $('#reset-colors').click(function(){
      $('#color1').val('#FFFFFF');
      $('#color2').val('#FFFFFF');
      });

  • Felix

    Thanks for the response Krike. I’m still not able to get it to switch the values in the form. I have a button with an id of reset-colors. Under that I have a function saying what you have above. Thanks again!

  • beachgypsy

    Thanks for this tutorial.
    I have downloaded your child theme and it works perfectly for the first color picker. I am able to change the color of my chosen element, no problem.

    But the second color picker does not work for me. It doesn’t enter the hex number, nor does it change the element that I have attached it to.

    It seems that this is the same problem that others have described previously. Was this fixed in the child theme download?

    Can you help with this?

    • @beachgypsy: You are right, I forgot to add the default value for the other color pickers. looks like frabtastic won’t work properly without a default value. I updated the child theme, The default value can be defined as follow:

      /*This should normally go into a seperate function to provide default values for when the theme is just activated*/
      $color1 = get_option('color1');
      if (empty($color1) || $color1 == '') {
      add_option('color1', '#002c84');
      }

      $color2 = get_option('color2');
      if (empty($color2) || $color2 == '') {
      add_option('color2', '#002c84');
      }

      $color3 = get_option('color3');
      if (empty($color3) || $color3 == '') {
      add_option('color3', '#002c84');
      }

  • Felix

    @beachgypsy,
    I’m thinking you probably have the same id and attributes name attached to the second color picker and the first color picker, if that makes sense at all? When duplicating the color picker and options you have to make sure that they have unique names for the id and update_options portion or else it won’t work. Hope that helped?

    Felix

  • I have a better, more dynamic way of adding those color pickers. I will be posting it soon.

  • Felix

    Hey Krike,
    Your color picker works great. I was wondering If I could use this within a theme I’m planning on selling, and if so do you have a personal website so I can direct people to it.

    • @Felix: Of course you can use it in a theme. My personal website is http://christophedebruel.be but you can just send people here 🙂

  • Thanks for this great code. It would be great if there was some standard values which applies when you add this to your theme without having to go and save the settings. A reset button to the default values would be sweet also. Thanks anyhow for your work on this, much appreciated.

    • @YourTubeTheme: checkout this quick tip on how to add color pickers dynamicly. There you will setup color pickers with default values which you can still use even after you selected and saved a new color. http://blog.cmstutorials.org/freebees/how-to-create-color-pickers-with-frabtastic-dynamicly

  • Gary

    Anyone else get this to work with four or more color pickers? When I try to add extras it doesn’t save the values or display the hex numbers. I’ve carefully made sure to give each an unique id but it hasn’t helped.