1. Code
  2. WordPress
  3. Theme Development

How to Use WordPress Color Picker API

When the WordPress team releases a new version, they introduce some new features not only for users but for developers, as well. WordPress offers a lot of tools that make it easier to develop new fantastic themes or plugins. One of the latest API available for WordPress developers is the new Color Picker; this feature allows to replace the standard text field with a nice and user friendly color picker. In this tutorial, I’m going to show you how add the color picker inside your WordPress project.
Scroll to top

When the WordPress team releases a new version, they introduce some new features not only for users but for developers, as well. WordPress offers a lot of tools that make it easier to develop new fantastic themes or plugins.

One of the latest API available for WordPress developers is the new Color Picker; this feature allows to replace the standard text field with a nice and user friendly color picker.

In this tutorial, I’m going to show you how add the color picker inside your WordPress project. Let's get started.


Why It Can Be Useful

There are some interesting reasons why WordPress developers should implement colors choice using the new picker API:

For Users

  • It provides a quicker and easier way to choose a color.
  • Users don't have to worry about what format of color they have to type – hexadecimal, RBG and so on.
  • Generally speaking, it provides an overall better user experience.

For Developers

  • Your dashboard pages will be integrated with the WordPress user interface.
  • It provides an easier input validation of the value of the color field.
  • It results in a more professional final product because it's using native controls.

After we cover some of the main aspects of WordPress Color Picker, let’s add it inside our plugin or theme.


Include Color Picker Assets

Before continuing, I have to specify that Color Picker API was introduced with WordPress version 3.5 so in order to work through this tutorial, then make sure you have release 3.5 or later installed.

To add the color picker, you simply include a jQuery file and stylesheet file. The code lines below show you how to do that.

1
add_action( 'admin_enqueue_scripts', 'wptuts_add_color_picker' );
2
function wptuts_add_color_picker( $hook ) {
3
4
    if( is_admin() ) { 
5
	
6
		// Add the color picker css file       

7
		wp_enqueue_style( 'wp-color-picker' ); 
8
		
9
		// Include our custom jQuery file with WordPress Color Picker dependency

10
		wp_enqueue_script( 'custom-script-handle', plugins_url( 'custom-script.js', __FILE__ ), array( 'wp-color-picker' ), false, true ); 
11
	}
12
}

Note that when we have included the custom-script.js with wp-color-picker dependency. Now you can apply the color picker to your text fields inside your jQuery file.

1
(function( $ ) {
2
3
    // Add Color Picker to all inputs that have 'color-field' class

4
    $(function() {
5
        $('.color-field').wpColorPicker();
6
    });
7
    
8
})( jQuery );

Creating a Plugin That Uses The WordPress Color Picker

At this point, it's time to show how integrate the Color Picker inside a real plugin.

Here's what we are going to cover:

  • How to add a dashboard option page that simulates a theme settings page.
  • How to add settings fields that are prepared for the Color Picker.
  • How to validate and save inputs.

Step 1

Once you have set up your plugin inside your WordPress wp-content/plugins folder we are ready to get started. The image below shows how I've structured the plugin for this tutorial. 

Plugin Structure

Step 2

Inside color-picker-plugin.php file, write the comments with plugin info and create a new PHP class called CPA_Theme_Options. The code below shows all class methods we are going to implements step-by-step.

1
/*

2
Plugin Name: Color Picker API

3
Plugin URI: https://code.tutsplus.com

4
Description: Demo about the new Color Picker API

5
Version: 1.0

6
Author: code.tutsplus.com

7
Author URI: http://code.tutsplus.com

8
*/
9
10
/**

11
 * Main Class - CPA stands for Color Picker API

12
 */
13
class CPA_Theme_Options {
14
 
15
    /*--------------------------------------------*

16
     * Attributes

17
     *--------------------------------------------*/
18
 
19
    /** Refers to a single instance of this class. */
20
    private static $instance = null;
21
    
22
    /* Saved options */
23
    public $options;
24
 
25
    /*--------------------------------------------*

26
     * Constructor

27
     *--------------------------------------------*/
28
 
29
    /**

30
     * Creates or returns an instance of this class.

31
     *

32
     * @return  CPA_Theme_Options A single instance of this class.

33
     */
34
    public static function get_instance() {
35
 
36
        if ( null == self::$instance ) {
37
            self::$instance = new self;
38
        }
39
 
40
        return self::$instance;
41
 
42
    } // end get_instance;

43
 
44
    /**

45
     * Initializes the plugin by setting localization, filters, and administration functions.

46
     */
47
    private function __construct() { }
48
 
49
    /*--------------------------------------------*

50
     * Functions

51
     *--------------------------------------------*/
52
     
53
    /**

54
     * Function that will add the options page under Setting Menu.

55
     */
56
    public function add_page() { }
57
     
58
    /**

59
     * Function that will display the options page.

60
     */
61
	public function display_page() { }
62
      
63
    /**

64
     * Function that will register admin page options.

65
     */
66
    public function register_page_options() { }
67
    
68
    /**

69
     * Function that will add javascript file for Color Piker.

70
     */
71
    public function enqueue_admin_js() { }
72
    
73
    /**

74
     * Function that will validate all fields.

75
     */
76
    public function validate_options( $fields ) { }
77
    
78
    /**

79
     * Function that will check if value is a valid HEX color.

80
     */
81
    public function check_color( $value ) { }
82
    
83
    /**

84
     * Callback function for settings section

85
     */
86
    public function display_section() { /* Leave blank */ } 
87
    
88
    /**

89
     * Functions that display the fields.

90
     */
91
    public function title_settings_field() { }   
92
    
93
    public function bg_settings_field( ) { }
94
        
95
} // end class

96
 
97
CPA_Theme_Options::get_instance();

Step 3

First, let's implement the class constructor. The code below shows what the plugin will do when a new instance will be created.

It will:

  • add a new options page under the Setting section of WordPress admin menu
  • register settings fields inside the options page
  • add CSS stylesheet for the WordPress Color Picker
  • add a custom JavaScript file that calls Color Picker
  • set the options attribute with settings saved.
1
private function __construct() { 
2
3
    // Add the page to the admin menu

4
	add_action( 'admin_menu', array( &$this, 'add_page' ) );
5
	
6
	// Register page options

7
	add_action( 'admin_init', array( &$this, 'register_page_options') );
8
	
9
	// Css rules for Color Picker

10
	wp_enqueue_style( 'wp-color-picker' );
11
	
12
	// Register javascript

13
	add_action('admin_enqueue_scripts', array( $this, 'enqueue_admin_js' ) );
14
	
15
	// Get registered option

16
	$this->options = get_option( 'cpa_settings_options' );
17
}

Step 4

The next step covers how to add the options page and how to display it.

1
/**

2
 * Function that will add the options page under Setting Menu.

3
 */
4
public function add_page() { 
5
    
6
	// $page_title, $menu_title, $capability, $menu_slug, $callback_function

7
	add_options_page( 'Theme Options', 'Theme Options', 'manage_options', __FILE__, array( $this, 'display_page' ) );
8
}
9
10
/**

11
 * Function that will display the options page.

12
 */
13
public function display_page() { 
14
    ?>
15
	<div class="wrap">
16
	
17
		<h2>Theme Options</h2>
18
		<form method="post" action="options.php">		
19
		<?php 
20
			settings_fields(__FILE__);		
21
			do_settings_sections(__FILE__);
22
			submit_button();
23
		?>
24
		</form>
25
	</div> <!-- /wrap -->
26
	<?php	
27
}

Note that we have already written - inside the display_page() method - the code that will add the form, the fields and the submit button for registering page options.

Step 5

In this step we are going to implement the methods which will register and display two settings fields: Blog Title field and Background Color field. Both fields belong to the Theme Options section.

1
/**

2
 * Function that will register admin page options.

3
 */
4
public function register_page_options() { 
5
    
6
	// Add Section for option fields

7
	add_settings_section( 'cpa_section', 'Theme Options', array( $this, 'display_section' ), __FILE__ ); // id, title, display cb, page

8
	
9
	// Add Title Field

10
	add_settings_field( 'cpa_title_field', 'Blog Title', array( $this, 'title_settings_field' ), __FILE__, 'cpa_section' ); // id, title, display cb, page, section

11
	
12
	// Add Background Color Field

13
	add_settings_field( 'cpa_bg_field', 'Background Color', array( $this, 'bg_settings_field' ), __FILE__, 'cpa_section' ); // id, title, display cb, page, section

14
	
15
	// Register Settings

16
	register_setting( __FILE__, 'cpa_settings_options', array( $this, 'validate_options' ) ); // option group, option name, sanitize cb	

17
}
18
19
/**

20
 * Functions that display the fields.

21
 */
22
public function title_settings_field() { 
23
	
24
	$val = ( isset( $this->options['title'] ) ) ? $this->options['title'] : '';
25
	echo '<input type="text" name="cpa_settings_options[title]" value="' . $val . '" />';
26
}   
27
28
public function bg_settings_field() { 
29
	
30
	$val = ( isset( $this->options['title'] ) ) ? $this->options['background'] : '';
31
	echo '<input type="text" name="cpa_settings_options[background]" value="' . $val . '" class="cpa-color-picker" >';
32
    
33
}

Step 6

This steps is focused on validation. The code below show how to validate the two fields before saving them.

1
/**

2
 * Function that will validate all fields.

3
 */
4
public function validate_options( $fields ) { 
5
    
6
	$valid_fields = array();
7
	
8
	// Validate Title Field

9
	$title = trim( $fields['title'] );
10
	$valid_fields['title'] = strip_tags( stripslashes( $title ) );
11
	
12
	// Validate Background Color

13
	$background = trim( $fields['background'] );
14
	$background = strip_tags( stripslashes( $background ) );
15
	
16
	// Check if is a valid hex color

17
	if( FALSE === $this->check_color( $background ) ) {
18
	
19
		// Set the error message

20
		add_settings_error( 'cpa_settings_options', 'cpa_bg_error', 'Insert a valid color for Background', 'error' ); // $setting, $code, $message, $type

21
		
22
		// Get the previous valid value

23
		$valid_fields['background'] = $this->options['background'];
24
	
25
	} else {
26
	
27
		$valid_fields['background'] = $background;	
28
	
29
	}
30
	
31
	return apply_filters( 'validate_options', $valid_fields, $fields);
32
}
33
34
/**

35
 * Function that will check if value is a valid HEX color.

36
 */
37
public function check_color( $value ) { 
38
	
39
	if ( preg_match( '/^#[a-f0-9]{6}$/i', $value ) ) { // if user insert a HEX color with #    	

40
		return true;
41
	}
42
	
43
	return false;
44
}

If the user tries to insert the color code manually, the Color Picker notifies him or her that s/he has typed a invalid value on the submission form; however, color - though it may be wrong - will still be saved. The check_color() function takes care to validate the color input.

Step 7

This is the final step where we are going to include our JavaScript file that convert a simple text field in an useful color picker.

1
/**

2
 * Function that will add javascript file for Color Piker.

3
 */
4
public function enqueue_admin_js() { 
5
    
6
	// Make sure to add the wp-color-picker dependecy to js file

7
	wp_enqueue_script( 'cpa_custom_js', plugins_url( 'jquery.custom.js', __FILE__ ), array( 'jquery', 'wp-color-picker' ), '', true  );
8
}

Let's create the jquery.custom.js file.

1
(function( $ ) {
2
    $(function() {
3
        
4
        // Add Color Picker to all inputs that have 'color-field' class

5
        $( '.cpa-color-picker' ).wpColorPicker();
6
        
7
    });
8
})( jQuery );

If you try to activate the plugin, you should get an dashboard page with all fields like in the image shown below:

Final Admin Page

That's It!

In this tutorial, you have learned how to include the new Color Picker powered by WordPress. In the plugin demo I've shown you how to integrate the color picker in a real plugin but you can use the API where you need such as inside a meta box, a widget form and so on.

The Color Picker works with WordPress 3.5+, but if a user has a previous version your code will work. Make sure to validate each color input using the check_color() method shown in Step 6.

Now your plugins or themes will be more powerful and user friendly.