目次
Toolsetで作ったカラーピッカー(カスタムフィールド)の値(16進数)をcssのrgb()に入れたい。
カスタムフィールドのカラーピッカーの値を、いつものように「<?php echo post_custom(‘wpcf-color’); ?>」これで出力してみたところ、出てくる値は「#000000」この手のタイプ。
でも、事情によりどうしても、「000,000,000」の形で取り出したい!!!
ということで、やってみました。
両方同じphpファイル(wordpressテンプレートのカスタム投稿タイプ用single.php)に記述。
<?php
function hex2rgb($hex) {
$hex = str_replace("#", "", $hex);
if (strlen($hex) == 3) {
$r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
$g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
$b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
} else {
$r = hexdec(substr($hex, 0, 2));
$g = hexdec(substr($hex, 2, 2));
$b = hexdec(substr($hex, 4, 2));
}
$rgb = array($r, $g, $b);
//return implode(",", $rgb); // returns the rgb values separated by commas
return $rgb; // returns an array with the rgb values
}
?>
.box{background: rgba(<?php
$arr = hex2rgb(post_custom('wpcf-color'));
$result = implode(',', $arr);
echo $result;
?>, 0.8; ?>);}
これで無事にrgb値として扱えるので、おためしあれ。
コメント