The WPFolks app is out on iPhone and Android. Free, no ads. Download on the App Store Get it on Google Play
Skip to main content
Login Join
Snippet · PHP

Convert HEX Color to RGBA Format

Shared by Sumit Javia | Senior WordPress Developer · May 25, 2026

25 views
Back to Snippets

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;
}
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments