Welcome Guest! Login? Checkout
This post was written 1 year ago and therefore may not be as accurate as more recent posts.

Recently I have been working on a project where we needed to save CMB2 Colour Picker field as a RGB field. As great as CMB2 is, by default, the field is saved as hexadecimal field (like #FFFFFF). This makes sense as it is the most common ways to display colours on the internet.

However, should you wish to use the colour for maybe a gradient with an element of transparency, you’ll probably need RGBA values. Luckily, you can modify CMB2 so the RGB value is saved, and saved in an array.

Convert Hex to RGB In PHP

Luckily, converting hexadecimal fields to RGB is quite straightforward. Each 2 numbers are 2 values multiplied together (so FF is 15 * 15, which is 225). So we can multiply the first two characters of the hex code, then PHP function hexdec, to get the decimal value.

That works for 6 character hex codes, but what about 3 character hex codes? Well these are the same number multiplied together, so all we need to do is check if it’s a three or six digit hex code, and act accordingly.

Here’s the function that we are looking to create which converts Hex to RGB.

Save the RGB Value

Now you need to make sure that the value is saved whenever the post is saved. To the best of my knowledge, there isn’t a CMB2 hook that we can hook into when the post is saved. However, we can use the save_post hook to save the RGB value.

To do this, simply create a function that finds the hex field, and then saves it as an RGB array

A Word of Warning: This code assumes that the CMB2 nonce is called cmb2_nonce and the hex field is called cmb2_color_hex. Please check these before you use them.

Modified from How To Create Custom Meta Boxes in WordPress.

To Use

The above saves the array as a custom field. To use, simply call the cmb2_color_rgb as you normally would:-

‘;

I hope you find this code useful. I’m convinced there’s a better way of doing it, so I’d like to hear it if you do have a better way of doing it!

Update

Thanks to Webucator for producing a short video on this blog post. Nice touch! You can see it below.

 
 
 

Comments

Comments are closed.