WordPress | How To Add Custom Color Picker in WordPress Custom Options Panel

|
| By Webner

While building options panel in functions.php of your child-theme, we can create our custom color picker without using any plugins.

We have to follow these steps and for this color picker :

1. Add Canvas

<canvas id="image_canvas" width="246px" height="210px"></canvas>

2 . Add Input Field to store hexadecimal code of color selected

<div id="hex">

HEX: 

<input type="text" id="theme_options[brandcolorhex]" name="theme_options[brandcolorhex]" value="<?php esc_attr_e( $options['brandcolorhex'] ); ?>" onkeyup="changedhex(this.value);"></input>

<label>Ex: #FFFFFF</label>

</div>

3. Add Input Field to store rgb code of color selected

<div id="rgb">

RGB: 

<input type="text" id="theme_options[brandcolorrgb]" name="theme_options[brandcolorrgb]" value="<?php esc_attr_e( $options['brandcolorrgb'] ); ?>" onkeyup="changedrgb(this.value);"></input>

<label>Ex: 225,32,32  [Format: r,g,b]</label>

</div>

4. Add a Div with transparent background to show selected color

<div class="active" style="background-image: url(/*Path to a transparent image*/);">

<span title="Press OK To Select New Color">&nbsp;</span>

</div>

5. Getting already selected color from options panel

<?php 

$options = get_option( 'theme_options' ); 

$brandcolorhex = $options['brandcolorhex'];

$brandcolorrgb = $options['brandcolorrgb'];

?>

Here,

We are fetching the fields ‘brandcolorhex’ and ‘brandcolorrgb’ of the options panel i.e if these colors are already saved in options panel then we will show those initially.

6. Adding script to make Color Picker work

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 

<script type="text/javascript">

/****************To show saved colors initially********************/

$( document ).ready(function() {

           var brandcolorhex="<?php echo $brandcolorhex?>";

var brandcolorrgb="<?php echo $brandcolorrgb?>";

if(brandcolorhex!=""){

var rgb= hexToRgb(brandcolorhex).r+ ","+ hexToRgb(brandcolorhex).g + "," + hexToRgb(brandcolorhex).b;

$('#rgb input').val(rgb); //Adding saved value to rgb input field

}

           if(brandcolorrgb!="0,0,0"){

var str_array = brandcolorrgb.split(',');

           var hex = rgbToHex(str_array[0], str_array[1], str_array[2]);

   $('#hex input').val('#' + hex);  //Adding saved value to hex input field

$('div.active').css('background', '#' + hex); //showing color on div

}

});

function changedhex(brandcolorhex){

if(brandcolorhex!=""){

var rgb=hexToRgb(brandcolorhex).r + "," + hexToRgb(brandcolorhex).g + "," + hexToRgb(brandcolorhex).b;

$('#rgb input').val(rgb);

$('div.active').css('background', brandcolorhex);

}

}

function changedrgb(brandcolorrgb){

if(brandcolorrgb!="0,0,0"){

var str_array = brandcolorrgb.split(',');

            var hex = rgbToHex(str_array[0], str_array[1], str_array[2]);

$('#hex input').val('#' + hex);

}

}

/******Get Canvas and Place Color Picker********/

var canvas = document.getElementById('image_canvas').getContext('2d');
 // create an image object and get it’s source

var img = new Image();

img.src = /*Path to image of a color picker*/;

// copy the image to the canvas

$(img).load(function(){

canvas.drawImage(img,0,0);

});

function hexToRgb(hex) {

var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;

hex = hex.replace(shorthandRegex, function(m, r, g, b) {

return r + r + g + g + b + b;

});

                    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);

         return result ? {

r: parseInt(result[1], 16),

g: parseInt(result[2], 16),

b: parseInt(result[3], 16)

} : null;

}

function rgbToHex(R,G,B) {

return toHex(R)+toHex(G)+toHex(B);

}

function toHex(n) {

n = parseInt(n,10);

if (isNaN(n)) return "00";

n = Math.max(0,Math.min(n,255));

return "0123456789ABCDEF".charAt((n-n%16)/16)  + "0123456789ABCDEF" . charAt(n%16);

}

$('#image_canvas').click(function(event){

var colorcanvas = document.getElementById('image_canvas');

// getting user coordinates

var elemPos = colorcanvas.getBoundingClientRect();

var x =  event.clientX-elemPos.left;

var y = event.clientY-elemPos.top;

// getting image data and RGB values

var imagedata = canvas.getImageData(x,y, 1, 1).data;

var R = imagedata[0];

var G = imagedata[1];

var B = imagedata[2];  

var rgb = R + ',' + G + ',' + B;

// convert RGB to HEX

var hex = rgbToHex(R,G,B);

// making the color the value of the input

$('#rgb input').val(rgb);

$('#hex input').val('#' + hex);

$('div.active').css('background', '#' + hex);

});

</script>

Here functions changedhex(brandcolorhex) and changedrgb(brandcolorrgb) are to execute if the user changes the hexadecimal value of color so that rgb value of color can also change itself and the div can show the changed color and vice versa.

Functions hexToRgb(hex) and  rgbToHex(R,G,B) are created to change the hexadecimal color value to rgb value and vice versa.

Through statement

$(img).load(function(){canvas.drawImage(img,0,0);});

We are drawing the color picker image to the canvas.

On click of canvas ‘#image_canvas’ , we are executing the function in which we are getting the canvas through its id, then we are getting the user coordinates through

var elemPos = colorcanvas.getBoundingClientRect();

var x =  event.clientX-elemPos.left;

var y = event.clientY-elemPos.top;

getBoundingClientRect() is the function that is called by an element to return the size of that element and its position relative to the viewport. So in this above statement we are finding the position of the canvas.

clientX, clientY are the properties of mouse event to output the horizontal and vertical coordinates of the mouse pointer when the mouse button is clicked on an element.

So on subtracting the position of the canvas from the position of mouse pointer we can get the position where the user clicked on the canvas.

In statement

var imagedata = canvas.getImageData(x,y, 1, 1).data;

Function getImageData(x,y, 1, 1) copies the pixel data of width 1 from the selected coordinates on the canvas. We get the output  imagedata as an array of 3 pixel data- R,G, B which we can get through:

var R = imagedata[0];

var G = imagedata[1];

var B = imagedata[2];  

Through the statements,

$('#rgb input').val(rgb);

$('#hex input').val('#' + hex);

$('div.active').css('background', '#' + hex);

We are showing the selected color code to the input fields and changing the color in the div that shows the selected color :

blog1

Leave a Reply

Your email address will not be published. Required fields are marked *