WordPress has added a color picker in the core code from WordPress v3.5. Theme and plugin developers can now take advantage of this and add a color picker easily in their plugin or theme interface.
The WordPress color picker uses CSS3 Gradients for everything, so it looks really nice on most displays and it is very user friendly.
In this article I will show you how to add WordPress color picker easily inside the WordPress user interface.
What You Had to Do Before WordPress Color Picker?
Before WordPress 3.5 you had to go find a suitable color picker JQuery library, include in in your plugin or theme then integrate it with some additional code.
How to Add Color Picker Now?
Step 1) Enqueue the “wp-color-picker” jquery script and style
add_action( 'admin_enqueue_scripts', 'mw_enqueue_color_picker' ); function mw_enqueue_color_picker( $hook_suffix ) { // first check that $hook_suffix is appropriate for your admin page wp_enqueue_style( 'wp-color-picker' ); wp_enqueue_script( 'my-script-handle', plugins_url('my-script.js', __FILE__ ), array( 'wp-color-picker' ), false, true ); }
My plugin now has a my-script.js file that has declared wp-color-picker as a dependency. We can now use the wpColorPicker jQuery method inside it.
Step 2) Add an input (example: text input) to the interface where you want the color picker
<input type="text" value="#bada55" />
You can also specify a default color for the field (this will be selected by default):
<input type="text" value="#bada55" data-default-color="#effeff" />
Step 3) Call “wpColorPicker” object from your script
Remember that we enqueued my-script.js above? Open it up, and be prepared for some long coding:
jQuery(document).ready(function($){ $('.my-color-field').wpColorPicker(); });
That’s it. Your users will now be able to choose a color from the color picker
Browser Support for This Color Picker
This color picker will work fine on IE8+ and all other major browsers.