WordPress has added a color picker in the core code from WordPress v3.5.Plugin developers can now take advantage of this and add a color picker easily in their plugin
How to Add Color Picker
Step 1) Create a java script named as color-script.js and place this code:
jQuery(document).ready(function($){ var myOptions = { // you can declare a default color here, // or in the data-default-color attribute on the input defaultColor: false, // a callback to fire whenever the color changes to a valid color change: function(event, ui){}, // a callback to fire when the input is emptied or an invalid color clear: function() {}, // hide the color picker controls on load hide: true, // show a group of common colors beneath the square // or, supply an array of colors to customize further palettes: true }; $('.my-color-field').wpColorPicker(myOptions); });
Step 2) Enqueue the “wp-color-picker” jquery script
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('js/color-script.js', __FILE__ ), array( 'wp-color-picker' ), false, true ); }
My plugin now has a color-script.js file that has declared wp-color-picker as a dependency. We can now use the wpColorPicker jQuery method inside it.
Step 3) Add an input (example: text input) to the interface where you want the color picker
<input type="text" value="#abc" class="my-color-field"/>
You can also specify a default color for the field (this will be selected by default):
<input type="text" value="#bada55" data-default-color="#abc" class="my-color-field"/>
That’s it. Your users will now be able to choose a color from the color picker
Have any doubt, then comment here!
Hi, thank you very much for this info!