Hex to RGB in GeneratePress

tdrayson

Sam Lomeli came up with a great idea for being able to use the GeneratePress global colours with transparency.

The Idea

Convert all the global colours in GeneratePress to their own RGB variable automatically.

This would then allow us to use the variable inside of RGBA()css function without losing the ability to globally update the opacity colours.

How It works

The snippet below will create new CSS variables of every GeneratePress global colour. It will append -rgb to the css variable name.

If you have a colour called accent, it will generate the css variable as accent-rgb. This can then be used to in the RGBA function like so:

Example: rgba(var(--accent-rgb), 0.7); which would give us a 70% opacity of our accent global colour.

The Snippet

Add the code below to functions.php or code snippet plugin.

PHP

        /*
 * tct_hex_to_rgb_conversion
 *
 * @function Convert global colours to RGB variables
 * @author Taylor Drayson
 * @since 24/04/2023
*/
add_action( 'wp_head', 'tct_hex_to_rgb_conversion' );
function tct_hex_to_rgb_conversion(){
    
    $colours = generate_get_option( 'global_colors' );
    $rgb_colours = '';
    
    foreach($colours as $colour){
        $name = $colour['name'] . '-rgb';
        $rgb = tct_hex_to_rgb($colour['color']);
        $rgb_formatted = implode(', ', $rgb);
        $rgb_colours .= "--$name: $rgb_formatted; ";
    }
    
    echo '<style>:root{'. $rgb_colours .'}</style>';
}

function tct_hex_to_rgb($hex, $alpha = false) {
   $hex      = str_replace('#', '', $hex);
   $length   = strlen($hex);
   $rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
   $rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
   $rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
   if ( $alpha ) {
      $rgb['a'] = $alpha;
   }
   return $rgb;
}

      
Copy

👋🏻 Weekly Tutorial Digest

I send out a weekly newsletter with links to new tutorials written in the last week, you can subscribe below.

Newsletter

🔒I won't send you spam, I promise