wp_customize color picker- Converting a hex value to rgba

I’m using wp_customizer’s color picker for the user to select the color of a div, but the opacity of that chosen color will be pre-determined, so I don’t need an opacity slider on the color picker UI.

Here is the color picker code, inside functions.php

    $wp_customize-> add_setting('primary_color', array(
    'default' => '#edeaea'
    ));
$wp_customize-> add_control( new WP_Customize_Color_Control($wp_customize, 'primary_color', array(
    'label' => __("Edit the primary color", 'portfolio'),
    'section' => 'colors',
    'settings' => 'primary_color' 
   ) ));

And i’m setting the style like this:

<style type="text/css">
    .header{ background-color: <?php echo get_theme_mod('primary_color'); ?>}
</style>

this returns a hex value, could someone advise how to convert the above value to a rgb value, and use this value to set a transparent color.

I have tried something like this:

function convertHex(hex,opacity){
hex = hex.replace('#','');
r = parseInt(hex.substring(0,2), 16);
g = parseInt(hex.substring(2,4), 16);
b = parseInt(hex.substring(4,6), 16);

result = 'rgba('+r+','+g+','+b+','+opacity/100+')';
return result;
}

$rgba = convertHex(<?php echo get_theme_mod('primary_color'); ?>,50);

I think the logic is there, but I’m not confident with the .php syntax how to use the result variable to change the style.

Read more here: wp_customize color picker- Converting a hex value to rgba

Leave a Reply

Your email address will not be published. Required fields are marked *