Home › Forums › Front-end Issues › Convert hexadecimal value to HSL › Reply To: Convert hexadecimal value to HSL
<?php
$hex = get_field(‘hex_color’);
echo ‘get field = ‘.$hex.'<br/>’;
$hex = str_replace(‘#’, ”. $hex);
echo ‘str replace = ‘.$hex.'<br/>’;
echo hexToHsl($hex);
?>
Just check it gets to that point ok i.e. a hex value without the hash.
If so, after this, add the following:
<?php
$red = hexdec(substr($hex, 0, 2)) / 255;
$green = hexdec(substr($hex, 2, 2)) / 255;
$blue = hexdec(substr($hex, 4, 2)) / 255;
$cmin = min($red, $green, $blue);
$cmax = max($red, $green, $blue);
$delta = $cmax - $cmin;
if ($delta == 0) {
$hue = 0;
} elseif ($cmax === $red) {
$hue = (($green - $blue) / $delta);
} elseif ($cmax === $green) {
$hue = ($blue - $red) / $delta + 2;
} else {
$hue = ($red - $green) / $delta + 4;
}
$hue = round($hue * 60);
if ($hue < 0) {
$hue += 360;
}
$lightness = (($cmax + $cmin) / 2);
$saturation = $delta === 0 ? 0 : ($delta / (1 - abs(2 * $lightness - 1)));
if ($saturation < 0) {
$saturation += 1;
}
$lightness = round($lightness*100);
$saturation = round($saturation*100);
But at various points, check the outcome, ensure the function works as you expect
For me, this works:
<?php
function hexToHsl($hex){
$red = hexdec(substr($hex, 0, 2)) / 255;
$green = hexdec(substr($hex, 2, 2)) / 255;
$blue = hexdec(substr($hex, 4, 2)) / 255;
$cmin = min($red, $green, $blue);
$cmax = max($red, $green, $blue);
$delta = $cmax - $cmin;
if ($delta == 0) {
$hue = 0;
} elseif ($cmax === $red) {
$hue = (($green - $blue) / $delta);
} elseif ($cmax === $green) {
$hue = ($blue - $red) / $delta + 2;
} else {
$hue = ($red - $green) / $delta + 4;
}
$hue = round($hue * 60);
if ($hue < 0) {
$hue += 360;
}
$lightness = (($cmax + $cmin) / 2);
$saturation = $delta === 0 ? 0 : ($delta / (1 - abs(2 * $lightness - 1)));
if ($saturation < 0) {
$saturation += 1;
}
$lightness = round($lightness*100);
$saturation = round($saturation*100);
return "hsl(${hue}, ${saturation}%, ${lightness}%)";
//return array($hue, $saturation, $lightness);
}
$hex_color = 'fff000';
echo hexToHsl($hex_color);
Returns: hsl(56, 100%, 50%)
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
In this article, we take a close look at WordPress custom fields and compare them to the custom fields possible with ACF: https://t.co/hk3yibkHyk
— Advanced Custom Fields (@wp_acf) July 14, 2022
© 2022 Advanced Custom Fields.
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.