Theme Options pages get quite sophisticated these days, providing the end user with a highly customizable WordPress experience. Our topic today is color and color pickers, which can be used to provide the theme user with an option to choose colors for different things like the footer area, the general text color, the navigation menu background color, headings color and so on. Of course all of this can easily be done by simply providing a Custom CSS field, but let’s admit that not everybody’s fluent in CSS.
Today we’ll talk about Farbtastic, a jQuery color picker script that is shipped together with WordPress. We’ll create a Theme Options page with a single text field and I’ll show you how to pop out the color wheel when the user clicks that field, as well as save and use the saved color in your theme afterwards.
Getting Started
First of all you should get familiar with the WordPress Settings API. Although you can copy/paste your way through this tutorial, I do recommend you read this great post by Chip Bennett called Incorporating the Settings API in WordPress Themes.
You should also be familiar with what actions in WordPress are and functions like get_option, wp_enqueue_script and of course add_theme_page. We’ll use those and other functions to:
- Create a Theme Options Page
- Register a setting, a section and a field (a color field) using the Settings API
- Enqueue a few scripts and styles on our Theme Options page
- Create a text input to hold our color value
- Attach Farbtastic to the color field
Ready? Let’s roll.
Creating a Theme Options Page
First things first, a Theme Options page. We’ll use the add_theme_page function and fire it during the admin_menu WordPress action as suggested by the administration menus entry in the Codex. I’ll be using my_ as the prefix for all the functions but you’re free to use your own, and/or wrap it up in an object-oriented fashion if you’d like to. Here’s the first few lines of our functions.php file:
function my_admin_menu() {
$page = add_theme_page( 'Theme Options', 'Theme Options', 'edit_theme_options', 'my-theme-options', 'my_theme_options' );
add_action( 'admin_print_styles-' . $page, 'my_admin_scripts' );
}
add_action( 'admin_menu', 'my_admin_menu' );
This creates a new entry under the Appearance menu called Theme Options which is rendered by the my_theme_options functions that we have provided. Note that we’re saving the output of the add_theme_page function into a variable called $page. We then add a function called my_admin_scripts to the admin_print_styles- hook prefixed with our $page.
This may look weird at first, but it really is quite simple. The admin_print_styles-x action is called whenever it is time to print the stylesheets on the x page. We’ll use this action to enqueue our javascript files later, but basically we’re telling it to call our function only when it is time to print stylesheets on that $page we have just added to the menu.
Read more about it in this codex entry: Load scripts only on plugin pages which is of course adapted to our theme and simplified a little bit.
Let’s go ahead and create the my_admin_scripts function and leave it empty for now, we’ll get to that in a while.
function my_admin_scripts() {
// We'll put some javascript & css here later
}
Let’s move on to the actual theme options page contents which is rendered by the function called my_theme_options. We’ll move on to the more difficult bit (the settings registration) after that.
Theme Options Page Contents
Hopefully you’ve seen such pages in the past and this is no different. You’ll be very familiar with the contents of the page if you’ve worked with the Settings API before. Here’s our my_theme_options function which has been provided as a callback to the add_theme_page call earlier.
function my_theme_options() {
?>
<div class="wrap">
<div id="icon-themes" class="icon32" ><br></div>
<h2>My Theme Options</h2>
<form method="post" action="options.php">
<?php wp_nonce_field( 'update-options' ); ?>
<?php settings_fields( 'my-theme-options' ); ?>
<?php do_settings_sections( 'my-theme-options' ); ?>
<p class="submit">
<input name="Submit" type="submit" class="button-primary" value="Save Changes" />
</p >
</form>
</div>
<?php
}
The simple markup makes the page look like a WordPress native page, with an Appearance icon and the appropriate heading. The form contains calls to wp_nonce_field, settings_fields and do_settings_sections as suggested by the Settings API. Finally we render a submit button called Save Changes. We could have used a sweet submit_button function here, but that would limit compatibility to 3.1 :)
If you browse to your Theme Options page at this point, you’ll see a blank page titled My Theme Options and a Save Changes button which doesn’t really work yet. The rest is up to the Settings API to define what sections and fields will be rendered on our page. Note that I used the my-theme-options key for the function calls in the snippet above, we’ll have to use the same key when registering our options.
Settings, Sections and Fields
This part should probably go before the theme options page contents, but since it’s a little bit more difficult to understand we left it down here. We’ll basically hook to the admin_init action and register one setting, one section and one field that will go into our theme options form that we have created earlier.
Here’s the code for the my_admin_init function:
function my_admin_init() {
register_setting( 'my-theme-options', 'my-theme-options' );
add_settings_section( 'section_general', 'General Settings', 'my_section_general', 'my-theme-options' );
add_settings_field( 'color', 'Color', 'my_setting_color', 'my-theme-options', 'section_general' );
}
add_action( 'admin_init', 'my_admin_init' );
As simple as that. One setting, one section and one field using register_setting, add_settings_section and add_settings_field respectively. You might also have noticed that I’ve got two more functions which I used as callbacks for the section and the field.
The section callback simply renders some info text about the General Settings section, here’s what my says:
function my_section_general() {
_e( 'The general section description goes here.' );
}
While the field is a little bit more complicated.
The Color Field
Let’s start with a simple text input that would contain our color value and be able to save it. Note that I’m not doing any options validation for brevity but you probably should. Here’s how the simple version of my_setting_color will look like:
function my_setting_color() {
$options = get_option( 'my-theme-options' );
?>
<input type="text" name="my-theme-options[color]" value="<?php echo esc_attr( $options['color'] ); ?>" />
<?php
}
At this stage you’ll notice that your new text input appears in your theme options page and actually works. Go ahead and type in anything in the input field and hit Save Changes, you’ll see that your new value is being saved.
Now you can start using that color value in your template files already, with a simple call to get_option and the output of the color key inside the returned array. Right, but our tutorial is about the slick color wheel, remember? Let’s move on to Farbtastic.
Attaching Farbtastic
As mentioned earlier, Farbtastic is a jQuery plugin that is shipped together with WordPress. We’ll use it to render a color wheel when the user clicks our color field input. We’ll stick to the basic Farbtastic usage, but if you explore the docs you’ll see that there’s quite some cool stuff you can do with that.
In order to use Farbtastic we’ll also need a javascript file of our own. Let’s call it theme-options.js and put it in a directory called js inside our theme folder. We’ll get to the contents of that file very soon, but now let’s get WordPress to load it (and Farbtastic too).
Remember the function called my_admin_scripts where we said we’ll squeeze in a few javascript and stylesheets inside? Well now is the time, here’s the new contents for the function:
function my_admin_scripts() {
wp_enqueue_style( 'farbtastic' );
wp_enqueue_script( 'farbtastic' );
wp_enqueue_script( 'my-theme-options', get_template_directory_uri() . '/js/theme-options.js', array( 'farbtastic', 'jquery' ) );
}
Quite easy to follow along, right? Include the Farbtastic stylesheet and javascript and then load our own (still empty) javascript file. I have also provided farbtastic and jquery as dependancies for our script to make sure that it gets loaded after those two have.
Let’s now revisit our my_setting_color function and change the markup a little bit to make it suitable with Farbtastic. What we need is an extra div that will hold our color picker as well as id attributes on both elements. I have also wrapped the whole thing up into a div and gave the elements some basic styling. This should probably be done with an external CSS file but if it’s that minor we’re okay :)
Here’s the contents of the new my_setting_color function:
function my_setting_color() {
$options = get_option( 'my-theme-options' );
?>
<div class="color-picker" style="position: relative;">
<input type="text" name="my-theme-options[color]" id="color" />
<div style="position: absolute;" id="colorpicker"></div>
</div>
<?php
}
The position relative/absolute hack is to make sure that the color wheel pops up on top of any elements existing on the page. This will prevent our Save Changes button from jumping up and down whenever the color picker is shown or hidden.
If you save changes at this point you won’t notice any difference. Right, because we have only prepared to use Farbtastic, but haven’t actually used it yet. That’s up to our javascript file.
Behold! The Color Picker!
Okay, you can simply copy/paste the code into your javascript file, see how that works and then return back here to read what it actually does ;)
jQuery(document).ready(function($) {
$('#colorpicker').hide();
$('#colorpicker').farbtastic('#color');
$('#color').click(function() {
$('#colorpicker').fadeIn();
});
$(document).mousedown(function() {
$('#colorpicker').each(function() {
var display = $(this).css('display');
if ( display == 'block' )
$(this).fadeOut();
});
});
});
So, first thing we’ll do is hide the color picker element and then initialize Farbtastic on that. Then we register a click event handler for our color field and make the color picker fade in. The last part of the code makes sure that the color picker is hidden whenever we click anywhere else on the page.
And that’s about it!
Conclusion
You’ve now got your very own color field inside your Theme Options page. With a little help from the Farbtastic docs you’ll be able to use it with multiple fields, style the color picker however you like and with some javascript magic you can add a Restore button that would restore the color to a default one. Just like the Background color feature provided by WordPress.
As mentioned earlier you can use the color value anywhere in your template files (or better yet in your wp_head section) with a call to get_option, like this:
function my_wp_head() {
$options = get_option( 'my-theme-options' );
$color = $options['color'];
echo "<style> h1 { color: $color; } </style>";
}
add_action( 'wp_head', 'my_wp_head' );
Which would colorize your first level headings. Of course the whole code is far from perfect, you should validate all incoming options, escape all options output, etc. Imagine if $color has been set to red; display: none; and the code snippet above. That would actually hide all your heading tags. You can’t make it absolutely hack-proof I know, but you should at least try to.
That’s all for today, hope you learned something new and enjoyed our tutorial. Ask questions, provide feedback and tell us if this helped you fine tune your WordPress theme. Use the comments section below to leave your thoughts and thank you for subscribing to our RSS feed.






Looks like you are calling id #colorpicker in your js when it should be .colorpicker. Does this work with multiple color pickers on the page?
John thanks for the heads up, seems like Markdown has stripped my
idattributes together with thenameattributes. Corrected the post. Yes, with some slight modifications and by using class names instead of IDs you can get this to work with multiple color fields as mentioned in the conclusion part.Thanks again for your comment!
Oops sorry missed that part. Here’s some modified code to make it work with multiple pickers on the page if anyone is interested.
Gist: https://gist.github.com/1181262
Wow, thanks for sharing this John! You can even get rid of that extra
id='colorpicker'part since you’re not using it anyway :)oh true, good call!
thanks, these are great tutorials to start going beyond the basics!
You’re welcome Paul, thanks for showing your support, we really appreciate that :)
Really useful article, thanks. I’ve been looking for a tutorial for creating a theme options page and this does the job!
Hey Andy ou’re welcome, glad it was useful :) Thanks for your comment!
Nice write up as usual. The way you guys advocate the WordPress core code standards is plausible. This would be even sweeter when the new settings API gets revealed soon.
Just a note that you can use
<?php screen_icon( 'themes' ); ?>instead of<div id="icon-themes" class="icon32" ><br /></div>. The final result is the same, but the WP core code uses the former.Sweet! Thanks for the tip Tacklr, that’s certainly the right way to do it. Also maybe worth mentioning that
screen_iconhas been introduced in WordPress 2.7 so can (and should) be used without worrying about compatibility, unlikesubmit_buttonfor example that’s been introduced in 3.1.Thanks again for the tip and your kind words :)
Also you can simply use
<?php screen_icon(); ?>, it will return icon for current_screen.Sweet! And even more generic :) thanks for the tip!
Great post, thanks for this.
You’re welcome, thanks for your comment :)
Hey Konstantin! First, thanks for the great post…!
I’m trying to implement this on the admin backend of my theme. It works almost properly. The Colorpicker appears when you click the field, but it only changes the back color of the field without inserting any hexa number into it. IF you write something yourself into the field… then it DOES return there the hexa value of the color.
Any clues about why is this happening?
Hi Javier, you’re welcome! Paste your code on Gist and give us a link, we’ll take a look :)
Thanks alot for a great tutorial, new developer here, seems so simple and yet I have spent days trying to get this to work in changing a:link text. The picker is showing fine and hex values show properly but I fail to understand how to “attach” it to anything. I read what you said about get_option, and I am still lost. Could you give me a quick code example of how to attach text color for example? I feel like if I could just see it, it would all make since somehow, hehe. Thanks again, and sorry for the newbie question.
Hey there coder, use a real name to avoid our anti-spam next time :) Anyhow, didn’t quite get your question about attaching. If you were able to render the text field in your theme options and get the color picker to show up, that’s good. If you were able to get the color picker to change the hex value in your text field, that’s even better. And if you were able to save that hex value when hitting Save Changes, that’s the best.
All that’s left is to actually use that value somewhere in your theme and there’s an example usage with
wp_headin the conclusion part of the article, have you tried that? If you’re targeting links then changeh1toa, a:link, a:visitedand if that doesn’t help try adding an!importantdirective. To debug that view the source of your page on the front end, it should be all there in the head section :)Thanks for your comment and let me know if you have any further questions!
You are right, I do have the picker working, even seems to save. My biggest accomplishment thus far, thank you Konstantin. My problem is that my theme options page does everything through arrays like this:
http://net.tutsplus.com/tutorials/wordpress/how-to-create-a-better-wordpress-options-panel/
I am confused between the class and id or $shortname to call somehow.
Or is this even possible to call through an array? My apologies for the newcomer questions and sincerely appreciate the guidance. I’m trying the wp_head suggestion now ..
Hey Robin, nice tutorial on nettuts, but a little bit of a different approach as it seems like they’re creating their own sort of API for field elements which is kind of redundant with the native Settings API around. I suggest you try the native way for options panel and a good tutorial to start with is Chip’s Settings API in WordPress themes. It’s quite long and very thorough but you’ll master the thing as you finish that :)
As for the arrays question, the
get_optionandupdate_optionare wrappers to thewp_optionstable in WordPress which has an option name and value fields. WordPress can do some cool stuff like serialize your array if you pass it on toupdate_optionso yes, it’s quite a good practice to store your plugin options in only one option entry but as an array for different keys and that’s basically what the Settings API implements.Let me know if I can do anything else to help!
Thanks so much for the advice, I have in fact considered using the native settings API after reading some theme authors opinions but I have 9 months sunk into it. Really hard to turn back now but it looks like I may have to considering finding help on this subject is null. You were my last hope. *sigh*. I really like how professional it looks and how easy it has been to otherwise set options up for it..until this dreaded color picker. Who would of thought setting up a color picker for text would be so difficult through an array. Thanks for all your advice, you have definitely given me food for thought. Thanks.
Robin, it’s not difficult you just have to follow a different pattern. Look at Step 7 in that tutorial and see how you can add another
caseblock for"color"and then usetype => "color"when defining your field.But again, consider using the Settings API for theme and plugin options pages. You can add an extra CSS to style your forms and fields however you want if you don’t like the “look” of the native way :)
Cheers!
I will, and am taking your advice. After finishing my first theme I will never do it this way again. I have basically re-invented the wheel. Not good. hehe. But hey, professionally speaking, I like cutting edge. In my quest to stand out from the rest I have painfully learned that this was not the best way to do this while learning. I sincerely appreciate you taking out the time to assist. The tutorial is amazing, can’t believe I missed this one. Oh, and one more huge thank you to pointing me in the right direction, this is exactly what I needed.
You’re welcome Robin, glad to have helped!
Hey Konstantin, thanks for answering so soon!
I have built the options panel in Chip’s way, and everything works perfectly. The problem I having is that no matter how many times I pick a color in the color picker (farbtastic) the value wont get into the field. I have inserted exactly the same code you provide here, and nothing. The only time it WILL put the value in the field is if I wrote something into it first. Do you get it? It’s like, it will replace some value with the color I chose, but if the field is empty it wont put anything into it.
What could I do?
Add a default value for the field such as #ffffff
Hey John!
Well… yes. That’s the other solution I came to (although I’m nothing happy with that, it’ll look like it is already chosen, and that bothers me from the UI point of view, but..) and since then I’ve been hitting my head against the wall, after discovering that there is one little reset button that is not working for that section, not related to this… just sharing my sleepless pain with yo ;) . Anyway, yes, if there is no other solution I’ll go to that, I just try to mimic the way WP uses farbtastic, and it should work like that, no?
Javier,
Good question. Seems like it’s a Farbtastic issue when using the default callback function. I was able to explicitly set the value of the form field by providing my own callback, replacing this line in the javascript:
With something like this:
I found this solution by inspecting the sources of Twenty Eleven, it declares a function called
pickColorand uses it as the callback for Farbtastic calls. Hope this helps :)Great!
I implemented what I had thought about before setting a “#” as default value of the field, which seems also good from a UI point of view. It worked right away.
Anyway, I’ll try what you did and decide later on which path to go.
Thanks so much for that little but awesome tip! :)
You’re welcome, let us know if that worked for you!
I will!
Heh, thanks for retweeting this post Konstantin, I must’ve missed it when it was published :) I wasn’t aware of this bundled jQuery plugin, need to update my KC Settings plugin to use this.
I would suggest using Modernizr to load the plugin though, since WP 3.3′s dashboard is already using HTML5 doctype and some browsers (only Opera as of now?) already have the color picker feature builtin.
Thanks again!
Dzikri, I wasn’t aware of a native color picker input element in Opera, thanks for the heads up!
Hey Konstantin, you couldn’t put the entire code, where you place or download? I can’t do the tutorial after “The General section description goes here..” Help me please. Thanks.
Leo, the point of the tutorial is not to copy/paste your way through but to understand what you’re doing. If you couldn’t get past the Settings API section you should revisit Chip’s article on that and then come back. Thanks for your comment and good luck :)
Hey Konstantin,
Thanks for the great tutorial! I experienced the same issue as Javier, where the colour was only saved when I had already written something in the field. Making this replacement worked:
$.farbtastic('#colorpicker', function(a) {$('#color').val(a);
});
Just wanted to suggest that maybe you incorporate that change into the main tutorial for future users.
I can pick the color but it wont save… Did I miss something?
//Admin Color Picker
function my_admin_menu() {
$page = add_theme_page( 'Theme Options', 'Theme Options', 'edit_theme_options', 'my-theme-options', 'my_theme_options' );
add_action( 'admin_print_styles-' . $page, 'my_admin_scripts' );
}
add_action( 'admin_menu', 'my_admin_menu' );
function my_admin_scripts() {
wp_enqueue_style( 'farbtastic' );
wp_enqueue_script( 'farbtastic' );
wp_enqueue_script( 'my-theme-options', get_template_directory_uri() . '/js/theme-options.js', array( 'farbtastic', 'jquery' ) );
}
function my_admin_init() {
register_setting( 'my-theme-options', 'my-theme-options' );
add_settings_section( 'section_general', 'General Settings', 'my_section_general', 'my-theme-options' );
add_settings_field( 'color', 'Color', 'my_setting_color', 'my-theme-options', 'section_general' );
}
add_action( 'admin_init', 'my_admin_init' );
function my_section_general() {
_e( 'The general section description goes here.' );
}
function my_setting_color() {
$options = get_option( 'my-theme-options' );
?>
My Theme Options
<?php
}
Sorry the above code didnt post the form properly…
I needed to get the last inputted color to display after saving so I made some modifications. Firstly, I used the snippets mention by the following
Konstantin Kovshenin
John Turner
So my JS is here
jQuery(document).ready(function($) {
$(‘.pickcolor’).click( function(e) {
colorPicker = jQuery(this).next(‘div’);
input = jQuery(this).prev(‘input’);
$(colorPicker).farbtastic(input);
colorPicker.show();
e.preventDefault();
$(document).mousedown( function() {
$(colorPicker).hide();
});
});
$.farbtastic(‘#colorpicker’, function(a) {
$(‘#color’).val(a);
});
});
My HTML is here.
<input type="text" name="my-theme-options[color]" id="color" value="” style=”background-color:” />
Note that I call back the options in the Value Attribute and Style Background. So each time, a color is saved, the HEX code is displayed in the Text Value field and the field is the selected color.
Here I placed a default color if none is selected
<input type="text" name="my-theme-options[color]" id="color" value="” style=”background-color:” />
One can simply make it a variable to make things easier.
thanks for this. Also I like your about the author
“PHP MYSQL PHYTON and coffee” Cheers!
Great article. Well written as always, and everything done properly
Tip: if you add the following style to your #colorpicker instead of just “position : absolute” it will look just like built in WordPress:
z-index: 100; background: none repeat scroll 0% 0% rgb(238, 238, 238); border: 1px solid rgb(204, 204, 204); position: absolute;