how to add a color picker to your wordpress theme admin panel

by krike in General on 17 Dec 2010


There is a newer version of this tutorial, much easier and faster. Check out “How to add a color picker in your wp theme using frabtastic

Lot’s of authors on themeforest offer different styles and colors for their wordpress templates, but wouldn’t it be better to allow the user to choose his own colors? We would then only provide them with the website structure and main background styles/images and the user will be able to customize the colors of the main text, headings, … and so on.

So let’s not wait and dive right into it.


The requirements for this tutorial

In order to complete this tutorial you must have A basic uderstanding in HTML, jQuery, PHP and developing themes in WordPress.


Download the color picker

The first thing we will need to do is find and download a color picker, I choose for jPicker because it’s really easy to implement, it’s exactly what we need and you are free to include it into your premium templates (or other product). So go ahead and download jPicker.


create theme admin panel

We will quickly create a theme admin panel because the options should be available from the admin backend.

copy paste the following code into the functions.php of your theme, if you already have an admin panel for your theme, create a new function for a new page.

				//Create the admin block menu and subpages
				function themeoptions_admin_menu() 
				{
				add_menu_page('WP color picker', 'WP color picker', 10, 'wp_color_picker_options', 'wp_copickpage');
				add_submenu_page('wp_color_picker_options', 'Style options', 'Style options', 10,  'wp_color_picker_options' , 'wp_copickpage');
				}

				//register the admin pages
				add_action('admin_menu', 'themeoptions_admin_menu');

				//page function
				function wp_copickpage()
				{
					if ( $_POST['update_posttypeoptions'] == 'true' ) { color_option_update(); }
					?>
	
					<div class="wrap">
						<div id="icon-themes" class="icon32"><br /></div>
						<h2>Styles</h2>
						<form method="POST" action="">
							<input type="hidden" name="update_posttypeoptions" value="true" />
							<p><input type="submit" name="search" value="Update Options" class="button" /></p>
						</form>
	
					</div>
	
	
					<?php
				}//end of function wp_copickpage

			

I’ll quickly go over the code:

  • We start by creating a new menu block (that’s what the themeoptions_admin_menu() function is for, then we need to add it to the admin panel using the add_action() hook), we pass in different parameters and the most important one is the last one which links to a function that will display the color pickers and other options you might have defined.
  • Next we create the actual function with a basic form and we already added the code which will check if the form was submitted or not, if it was submitted we call a function which will process the form.

We’ll create that last function later on, this is how your menu should look like:

add the color pickers

To use the color picker we’ll need to add all of the files first to our theme, so copy all the files and try to keep the same structure (so js files in a folder js and stylesheets in a folder css). Also make sure you include the latest version of jQuery in your theme.

You might need to change the path to the images. Both from the css stylesheet and js files.

let’s add a new input with name and id inp-heading, this input will be populated with the hex value of the selected color.

			<p><input type="text" name="inp-heading" id="inp-heading" value="efefef" /></p>
		

now we need to use jquery to select the input field and apply the color picker on it. At the end of the function (before <?php) add:

			<script type="text/javascript">
	  		$(document).ready(
			    function()
			    {
			      $('#inp-heading').jPicker(
			        {
			          window:
			          {
			            expandable: true
			          }
			        });
			    });
			</script>
		

We set window->expandable to true so the big color picker is hidden by default until you click the small color preview. You should have something like this:

For some reason the color picker was set to -177px which moved it outside the page. So I quickly fixed this by modifing the jQuery plugin source code. Find the following code in jPicker-1.1.5.js:

			top: win.position.y == 'top' ? (popup.offset().top - 312) + 'px' :
		

And then just remove the – 312

			top: win.position.y == 'top' ? (popup.offset().top) + 'px' :
		

ok, now just choose a color, you will see the value of the input field change. if it works perfectly you can hide the input field because there is no need to display it.

			<p><input type="hidden" name="inp-heading" id="inp-heading" value="efefef" /></p>
		


save the colors in options

Alright, now that the form is ready and the color picker working we can save the hex value in a wordpress option. the good news is that we are already checking if the form is submitted and if it is we ar pointing to a function.

Let’s create that function, we called it color_option_udpate().

				function color_option_update()
				{
						//fetch hex value and save it an option
				}
			

Saving in a wordpress option is very easy. Just get the hex value using the $_POST global variable and save it to the database using the update_option() function provided by wordpress. It requires 2 parameters, the first one being the name of the option and the second the value that should be saved into the database.

				update_option('t_heading_color', $_POST['inp-heading']);
		

At this point you should normally validate the value stored in $_POST[‘inp-heading’], but for this tutorial we will skip it. (just make sure you don’t forget to validate)

create css file with php

To use the saved colors we need to create a dynamic stylesheet. Create a new file and name it dynamic_colors.php.

Next we need to include this new dynamic stylesheet in our theme. In the header of your theme add:

				<?php include('dynamic_colors.php'); ?>
			

Next we will add some css code in our dynamic stylesheet

				
			<style type="text/css">
			h1
			{
				color: #;
			}
			</style>

		

Now we need to get the value of the stored option and print it out in our stylesheet using the get_option() function provided by wordpress

				h1
				{
					color: #<?php echo get_option('t_heading_color'); ?> ;
				}
			

One last thing we should do is create a function that will automatically create all the options when the theme is activated, because if we don’t there won’t be any color displayed until the user selected one.

				//create the options with default values
			function create_default_options() {
			  add_option('t_heading_color', 'efefef');
			}
			register_activation_hook( __FILE__, 'create_default_options' );
			

Extra color pickers

Obviously the headings aren’t the only elements to require a color picker, depending on your theme you might want to add extra color pickers for different elements. Just follow the previous steps to add the new color pickers.

Let’s say you have a button with a background color and a slightly lighter border. You would create 2 different color pickers, one for the background and one for the border. You could do that or you could also use one color picker for the background and with the help of a php class generate a slightly lighter version of that color for the border. This will save you time and your customers lot’s of time.

download csscolor.php

There is a pretty cool php class that will create a color palette of a given color, you only need to specify which color on that palette you would like to use. The class is call Csscolor. Go ahead and download it and save it in your themes (don’t forget to unpack)


css button

Let’s say you have the following markup:

			<a href="#" class="button-link">Css button</a>
		

And the following css code:

			.button-link
				{
					display:block;
					background:#<?php echo get_option('t_button_color'); ?>; /* 0200AF */
					padding:3px 6px;
					border:1px solid #0300FF;
				}
		

Just above include the class file and create a new instance of csscolor and as parameter you pass in the option

			<?php
					include('csscolor.php');
					$button = new CSS_Color(get_option('t_button_color'));
				?>
		

Now all you need to do is specify for the border if you wan’t a lighter or darker color, so the css for your border would look like this:

			border:1px solid #<?php echo $button->bg['+2']; ?>
		

+2 being the position of the color, on the color palette, you wish to use.


conclussion

So there you go, in a few easy steps you learned how to add a color picker to your theme. This will save a lot of time for you and your customers. This way you offer unlimited ways of styling the wordpress theme instead of providing 1 or 4 color stylesheets.

Want more tutorials?

If you are looking for more webdesign & development tutorials or you would like to share your own written tutorials, visit the CMS tutorial site. Also subsribe to our rss feed.

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.

  • angel

    Its a very useful tutorial but have a small bug, if press update, change the color, but if you select other box and other color, the previus box retur to default color :s,

    now, i put in the input, the code , and its ok, save separated options, but, can’t return to default option….

    now, how can i agree a retet options button?

  • mike

    color picker not working in firefox 4. any ideas? it worked before i updated.

    thanks

    • @mike: thanks for letting me know, I’ll have a look as soon as possible.

    • @mike: Can you give a link somewhere where I can check why it’s not working? (send info to idealvisions[at]live[dot]com). I just installed Firefox 4 on my laptop and checked the administration panel of one of my themes that is using 12 color pickers and they appear just normally as expected

  • coder1

    I have tried everything to get this working. Everything seems to be working properly except 2 things.

    1) Half the images show and half do not. The map.png, picker.gif, and gradients while choosing a color are missing. Yet the pointer, slider, etc works fine. I have checked the paths 100 times and I cannot get these working.

    2) When you choose a color and click update it reverts back to the default color. Someone mentioned this earlier but with thier poor english skills it is beyond me to figure this out.

    Lastly, in your tutorial you say to include the dynamic_colors php file in the header. I have tried inserting this everywhere and in many different codex but it fails to work. Can you give me any insight as to how to get ALL the images working, get it to stop reverting back to default, and how to enter the include properly in the header? Thanks.

    • @coder1: sorry for my late response. To answer your question I first need to know how your project structure looks like. Without a preview to your code i can only guess. the dynamic_color.php needs to be included in a file which is present in all your webpages where you need the colors you selected from the color pickers. For more help you can always contact me at idealvisions[at]live[com]

  • Where to add this:

    • @Dave: sorry but could you refer to the paragraph or peace of code? You cannot paste code in the comments

  • Hi,

    I can’t get my jpicker loaded. Is the code correct?
    what’s that ?gt; use for?

    and why the is put inside the link? should it be outside?

    sorry for noob question.

    • @Dave: could you rephrase that because I have no idea what you are actually asking?

  • and by the way, i’m using the new version of jpicker 1.1.6. Will it be a matter? Because there’s no win.position.y

    • @Dave: the update might have changed a few things. i’m unable to look into it right now, better to use the same version as in the tutorial unless you can’t download it anymore? I still have a copy I think

  • Hi Christ,

    I’ve sent an email to you. Anyway, is there a way I can get the older jPicker version?

    Thanks,

    Dave

  • @christ: I have solved my problem and I can see the jPicker loaded. However, I just encountered new problems, the same problems as coder1 had.
    The textarea for H,S,V,R,G,B,# is smaller than font inside, so the text was cut here and there. The color picker vertical scroller also has no color on it.

    Is it the jPicker bug?

    • @Dave: It could be, I haven’t had time to test it out with the new version. You can download the version I used and let me know if you have the same problem. (on line 1890 you have to change the yourthemenamehere to whatever your theme name is)

  • @christ: I’ve tried the 1.1.5 version. The problem is still the same as coder1 had.
    Maybe I should try another jquery color picker script. I read farbtastic is quite good.

  • @Chris:
    Sure Chris. That would be good. Thanks a lot! 🙂
    It’s weird because me and coder1 are having the same issue with this color picker script. 🙁

  • dave

    @chris:
    Sure Chris, that would be great. I’ve been looking to find a way how to get this thing works.
    Thanks before.

  • dave

    @Chris:

    CMIIW, but I see some mistakes in your wrapped-up functions.php.
    1. You don’t call the function color_option_update() in that wrapped-up functions.php. That’s why the color changes never been saved.
    2. You have mentioned about “if ( $_POST [‘update_posttypeoptions’] = = ‘ true ‘ ) { color_option_update ( ) ; } ”
    But somehow you don’t use this code in your wrapped-up functions.php
    3. There are several “?gt;” symbol in your code. Maybe you should re-check your functions.php once again.

    • 1. that is not true, there is a hidden input with value true. The check in you second point is the check that will call color_option_update() once the form was submitted. If you want to see if that function was called just echo something out (eg:add in color_option_update(); the following code: echo "function was called";)
      3. there is no ?gt; in any of the code supplied in this tutorial

  • raj

    please help me to add color picker for the header,footer,and the background color of my theme

  • zeaks

    Thanks for this tutorial, it’s a bit over my head I’m new to adding admin options to themes but…

    @krike the ?gt; people are referring to is on line 19 and 20 of the “All the code in functions.php wrapped up” part. Looks like the syntax highlighter is messing with the code or something. Should be > I think instead.

    I couldn’t get this to work, but I did notice a couple issues with what I did get working that might help out. (not putting the tutorial down, just giving constructive feedback)

    The .js you supplied in the comments to Dave references your own theme ./wp-content/themes/creafolio/images/ on line 1890.

    In the 1.6 version of the jpicker the image directory is referred to as ./jpicker/images so I’m assuming the directory jpicker must exist.

    I could get the color picker to pop up, the adjustment you gave brought it down a bit, but also seemed to mess up the numbers and items in the picker though.

    The id=”icon-themes” class=”icon32 doesn’t exist and there is no style given for it in the tutorial (unless I’m missing something), I’m thinking maybe this is why the color picker link isn’t showing up as I can click around the “header color:” link and get it to pop up, there’s just no visible button/link to it.
    It seems worse in firefox, in IE and chrome a small grey square shows as you can see in the screenshot.

    in step 3 you say “now we need to use jquery to select the input field and apply the color picker on it. At the end of the function (before ” ….. before what?

    Last thing, the “All the code in functions.php wrapped up” seems to be different from the previous code and also missing some of the previous code.

    I’d love to be able to figure this out, please update it when you have time, it’s the only tutorial like that I was able to find.

    • @zeaks: thanks for your constructive comment 🙂 and sorry for my late response, been kinda busy lately. First thing first.

      I repeat my previous statement, i don’t see a ?gt; on line 19 & 20 of the wrapped up code, I even search the entire page with the search function and had no results
      I changed the js file and update my comment above 🙂
      I will quickly create a child theme with only the color pickers
      id=”icon-themes” class=”icon32 is from wordpress and should be know to wordpress, but i’ll add specific styles so you can modify the input fields
      About step 3, I’m terribly sorry, looks like I missed something there. I will update asap
      i will remove the wrapped up code and provide a child theme which you can experiment with

  • Here’s a screenshot it’s on 29 and 30. It’s supposed to be an > I think, looks like wordpress changed it in the post is all.

    • @zeaks: ah ok I see it, yes you are right. But anyway I will create the child theme which you can download and i’ll delete the wrapped up code like I said in my previous comment.

  • I created a working demo in a twentyten child theme. To download it click the link in the info box at the top of the page.

  • Thanks for taking the time to make this child theme. I’m unable to get the colorpicker to show in the options though, and when it saves, it shows
    Array
    (
    [update_themeoptions] => true
    [color_picker_color1] => 002c84
    [color_picker_color2] => 002c84
    [search] => Update Options
    )
    Here’s a screenshot, tried it in IE 8, 9, FF and chrome

    Any ideas?

    • @Zeaks: sorry I forgot to remove that, it was to check if something was actually posted (I updated the theme child). but I don’t experience that problem with the color pickers .. I have no idea. As you can see in this screenshot I have it working in FF, chrome & safari (not sure about IE thought) ->
      Is your site live? maybe I can have a look at it and see what’s wrong.

  • Sure, I have a test site can login with *********
    Thanks

    • @Zeaks: from what i can see the link to the jpicker css & javascript file is incorrect. it links to ‘wp-content/themes/twentyten’ while it should like to wp-content/themes/twentyten-child’. Is that a wordpress multisite? It’s weird I added get_bloginfo('template_url') for the path so it should normally woerk … unless that’s because it’s a wp multisite, i have one online I’ll test it there as well to see if that’s the problem. (ps: I removed the password, not really save to put that in a comment 🙂 )

  • fixed the typo in step 3 as well, it was a php opening tag causing the problem 🙂

  • Thanks, it’s working a bit better now, the color block is showing, but still seems to have a bad link. Maybe it’s just my server or something, I tried it on another site (same server) but it’s still showing the same as in the screenshot above when I hard linked the .js and .css. I’ll play around with it and try and figure out why it’s not working properly on mine.
    I did use this tutorial to add a color picker to my own theme, so thanks again 🙂

    • @Zeaks: I updated the tutorial yesterday to mention there is a link to the images on line 1890 of the jpicker javascript file, maybe you should check that link to see if it works, just hardcode the link to see if it works. I used ./ to link to the root but that might depend where on your site it was installed and the settings of your servers as well. (just guessing, can’t be sure thought).
      And you are welcome 🙂

  • hmm, that’s weird. It’s using template_url it should direct to the proper directory. In child themes I know using stylesheet_url directs to Twenty Tens directory so it should work. I tried changing it to a fixed link, which brought up the color picker “sort of”
    I’m not using MU, it’s just a regular install about two weeks old.

    • @Zeaks: oops i made a small typo on your site and it’s showing a fatal error but I can’t fix it. However I found the problem, when you go to http://codex.wordpress.org/Function_Reference/bloginfo you will see that ‘template_url’ links to the parent theme while ‘stylesheet_directory’ links to the child theme, so you should use that instead. I didn’t notice the problem because i have the exact same files in the twentyten parent theme, sorry about that. I updated the theme, you should remove your current twentyten child theme and upload the new one

  • Hi, Thanks for this, very useful tutorial. I have a question. I seem to have everything working correctly, except one thing… The color picker chooses and updates the front-end properly, but in the wp-admin area it seems that the color picker always revert to the default color values of #EFEFEF that’s being used. I think it’s a problem with the saved options being overwritten by the declared defaults… Any ideas on what I could be doing wrong? Thanks in advance.

  • Anne

    Hi,
    I am having the same problem as coder1 on 27 May 2011 in that some of the images load and others don’t. Since some of the images are loading I assume the paths are correct. The images that are not loading appear to be background images for the main map and the slider. Even though these are not loading (or at least not visible) they scrolling to get a color still works as if they were there.
    Any thoughts?

    • @Anne: hey, I have written a newer and better version of this plugin using a javascript library that is already available in WordPress. You can find it here -> http://blog.cmstutorials.org/reviews/general/how-to-add-a-color-picker-in-your-wp-theme-using-frabtastic

  • Sani soni

    Should this be slow because many database query?

    • @sani: it’s not that many db queries. But you can still check the page you are on and only caal those values when needed. For the frontend you could define constants so you only query the db once to get the values. Simething like define('color_picker_1', get_option('color1'); (it’s just a quick example).

      Of course there are other ways to optimize this but that was beyond the scope of this article.