This helper function converts a 6-digit HEX color code into an RGBA color value with predefined opacity. It is useful for generating transparent background colors dynamically in WordPress themes or plugins.
/**
* Convert a HEX color code to RGBA format.
*
* This helper function converts a valid 6-digit HEX
* color value into an RGBA color string with
* predefined opacity.
*/
function sj_convert_hex_to_rgba( $hex_color ) {
// Remove the '#' symbol if present.
$hex_color = ltrim( $hex_color, '#' );
// Validate 6-digit HEX color format.
if ( 6 === strlen( $hex_color ) ) {
// Convert HEX values to RGB.
$red = hexdec( substr( $hex_color, 0, 2 ) );
$green = hexdec( substr( $hex_color, 2, 2 ) );
$blue = hexdec( substr( $hex_color, 4, 2 ) );
// Return RGBA color with opacity.
return "rgba($red, $green, $blue, 0.1)";
}
return false;
}