Add Color Picker in Wordpress
Posted By : Satyam Sharma | 25-Apr-2018
Introduction
In our blog, I will show you how to add a color picker in our custom fields. Wordpress provide us color picker API to the WordPress developer. By using this API we can replace the textbox with a user-friendly color picker in WordPress backend as well as WordPress frontend. By using this we can choose a color so easy and so quick also.
Let you have a WordPress custom plugin and there is a text-box for background color and you know to remember the hexadecimal code of all color is not easy so you want to add a color picker in your custom option which automatically put the hexadecimal code of specific color. So for add a color picker at textbox you just have to follow the given steps :
Step one :
The First Step is to include our WordPress wp-color-picker script in our WordPress admin file. For this we use wp_enqueue_style( 'wp-color-picker') in our function and add this function through ' admin_enqueue_scripts' action hook.
For example:
/* wcp is used for wp-color-picker */
function wcp_theme_scripts() {
wp_enqueue_style( 'wp-color-picker');
}
add_action( 'admin_enqueue_scripts', 'wcp_theme_scripts' );
Step two :
The next step is to assign
For example:
<input type="text" name="background_color" value="<?php echo esc_attr( get_option('background_color') ); ?>" id="background_color">
Step Three :
The next step is to add a function to our custom js script by using 'admin_footer' action hook and write our js script in the given function. Put the WordPress color picker script in the text box through the given id of the text box.
For example:
add_action( 'admin_footer', 'wcp_custom_script' ); // Write our JS below here
function wcp_custom_script() { ?>
<script type="text/javascript" >
jQuery(document).ready(function() {
jQuery('#background_color').wpColorPicker();
});
</script> <?php
}
Note : Please make sure all the given id name and the function name should be unique. Because wordpress has many or much more functionality and if your given name would not be unique then it would be conflict and also your side could be stop . So give name like if we use wp-color-picker then add wcp prefix at all your function and id
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Satyam Sharma
Satyam Sharma is a skilled full-stack developer, who loves to get new opportunities and learning about new technologies.