Tutorial: How to add color picker to wordpress options page?

color

It is very easy to add colour picker with just 10 lines of code on the fly. I am gonna teach you how to use Iris colour picker to the input box in your wordpress options page. I am going to keep this very simple and short and i will not go deep on creating wordpress options page. I am assuming you know how to to create options page to your wordpress theme.

This colour picker we create will pop up when we click the input text box in the form and it will toggle hide when you click again. Further this will style the background of the selected colour to the input text box.

1. Before you start, download and copy the Iris.min.js from the distribution folder and paste into /yourtheme/js/.

3. Open your functions.php and copy these lines. This will initialise all the Iris package, to the admin area. This hook will enqueue the colour picker only inside the admin area.

add_action( 'admin_enqueue_scripts', 'softlights_color_picker' );
function my_color_picker() {
wp_enqueue_script( 'iris',get_template_directory_uri().'/js/iris.min.js' );
 wp_enqueue_script( 'iris-init',get_template_directory_uri().'/js/iris-init.js' );

}

3. Create a new javascript file iris-init.js and place it inside /mytheme/js/ folder, and copy the below code inside it.

jQuery(document).ready(function($){
 $('#color-picker').iris({
 width: 400,
 hide: true,
 change: function(event, ui) {
 // event = standard jQuery event, produced by whichever control was changed.
 // ui = standard jQuery UI object, with a color member containing a Color.js object
// change the headline color
 $("#color-picker").css( 'background', ui.color.toString());
 }

 });

 $(this).click(function() {
 $(this).iris('toggle'); //click came from somewhere else
});
});

4. Finally you have to call the color-picker where you want to appear. You have set id=”color-picker” to the element.

Color: <input type="text" class="color-picker" name="softlights-options[menu-color]" id='color-picker' value="#cc0000" />

Thats all! The colour picker should show up by default in your options page.

Multiple Color Pickers

The above code should work well without any issues with multiple colour pickers. If you are using multiple color pickers, you might want to tweak the code lite bit.

Set the id of the input to color-picker-1, color-picker-2 etc..

<input type="text" name="softlights-options[menu-color]" class="color-picker" id='color-picker-1' value="#cc0000" />
<input type="text" name="softlights-options[menu-color]" class="color-picker" id='color-picker-2' value="#cc0000" />