Over a million developers have joined DZone.
Platinum Partner

Add Color Picker to WordPress Admin Console

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix.  Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.

In a previous tutorial you would of learnt how you can create your own theme options page using the Settings API. You might of also seen the tutorial about default WordPress scripts which come with the WordPress core.

In this tutorial we are going to use both of these tutorials to create a colour picker on your theme options page using the default WordPress scripts.

When you create a field on your theme options page you use the function add_settings_field(), one of the parameters of this function is to name a callback function which displays the field on the page.

The below code will add a colour picker to your theme option page.

add_settings_field( 'example_colour_picker', 'Example Colour Picker', 'pu_display_colour_picker', 'pu_theme_options.php', 'pu_colour_section', array() );
add_action( 'admin_enqueue_scripts', 'enqueue_colour_picker' );
function pu_display_colour_picker($args){
     extract( $args );
     echo '
<div class="farb-popup-wrapper">';
     echo '<input type="text" id="'.$id.'" name="'.OPT_NAME.'['.$id.']" value="'.$value.'" class="'.$class.' popup-colorpicker" style="width:70px;"/>';
     echo '
<div id="'.$id.'picker" class="color-picker"></div>
     echo (!empty($desc))?' <span class="description">'.$desc.'</span>':'';
     echo '</div>
 * Enqueue the colour picker
function enqueue_colour_picker(){
			array('jquery', 'farbtastic'),
		wp_enqueue_style( 'farbtastic' );

The above code will use the add_settings_field() function to create a field of displaying the colour picker. Within the function we add an action to attach a function onto the admin_enqueue_scripts to add javascript to the page. This javascript will load the inbuilt default script of farbtastic, the colour picker.

We also load a Javascript file called Field_Color.js which we will use to attach elements to the farbtastic jQuery function.

Now create a Javascript file and add the following code.

	var $color_inputs = jQuery('input.popup-colorpicker');
		var $input = jQuery(this);
		var $pickerId = "#" + jQuery(this).attr('id') + "picker";

This searches for all elements with the class popup-colorpicker, with these items we can attach the farbtastic function to display the colour picker.




The Web Dev Zone is brought to you in partnership with Mendix.  Learn more about The Essentials of Digital Innovation and how it needs to be at the heart of every organization.


Published at DZone with permission of Paul Underwood , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}