Site icon StartFunction

How to add a color picker to your WordPress plugin or theme

One of the most useful options for a user of a WordPress theme or plugin is to be able to change and stylize the appearance and the colors of the output produced. In this tutorial we will learn how to add a color picker in the settings page of a plugin using the Farbtastic jQuery plugin bundled with WordPress.

Farbtastic, WordPress’ color picker.

Although the only reference to Farbtastic is in the WordPress Codex page for wp_enqueue_script, Farbtastic is used internally in WordPress to modify the background color. If you want to know more, you’ll have to head to Farbtastic home, where you will find a demo and enough documentation to get started.

We won’t be dealing with how to create an options page because that’s out of the scope of this tutorial. If you need one, check this settings tutorial by Otto, one of the Core Contributors to WordPress.

Adding the metabox for the color picker

This is what we need in our metabox. The two most important things are the color input field, which will store the color value in hexadecimal format, and the div named ilctabscolorpicker. This is where Farbtastic will create the color picker and setup the color wheel.

<tr valign="top">
<th scope="row">
<small>Click on each field to display the color picker. Click again to close it.</small>
<label for="color"><input type="text" id="color" name="color" value="<?php echo $value['color']; ?>" /> Pick link color</label>
<div id="ilctabscolorpicker"></div>

Feel free to replace the

 echo $value['color']; 

with your own method to retrieve the current value stored in the variable. Don’t forget to include the Farbtastic script and stylesheet in your theme if it’s not already loaded.

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

Creating the color picker

Now we only need to add some jQuery to do the magic. You can either add this below the previous code for the metabox or use a WordPress hook to include it in the footer of the admin.

<script type="text/javascript">

jQuery(document).ready(function() {


These sentences will actually create the color picker in the div. The first line will hide the color picker initialized in the second line. The third and final line adds an event listener to the color input field. Whenever it is clicked, the color picker will slide down. After you have selected your color, click on the input field again to hide the color wheel.

Advanced Farbtastic

Farbtastic also has an object mode that allows you to use some more advanced methods like a callback, an HSL color space and more. It’s a great solution to add a color picker  that is already baked into WordPress, making it very lightweight and most important, fully compatible.

Exit mobile version