Convert Hexadecimal to RGBA

When working with WordPress you sometimes have to make accommodations in your code. I came across one of these today when working with WordPress Theme Customization API. It has a great built-in color picker control which allows users to select a color from an easy-to-use interface.

The problem I ran into was that it output a hexadecimal value. Normally this isn’t a problem. Unfortunately, I wanted rgba. I had set up a second setting – a text input – which allowed a user to input an opacity. This is the fourth value in rgba. So I needed a way to convert the 6-digit hexadecimal into a 4-value rgba format.

The following Jist handles this. It strips out any ‘#’, determines if the input shorthand hexadecimal or not, and then converts that string into rgb format. I then add on an opacity value, which is default to 1.