Skip to content

Instantly share code, notes, and snippets.

@petertwise
Last active February 9, 2020 19:27
Show Gist options
  • Save petertwise/036290389ba97434b17ab959a0ce9aef to your computer and use it in GitHub Desktop.
Save petertwise/036290389ba97434b17ab959a0ce9aef to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: Square Candy ACF RGB color output
Plugin URI: http://squarecandydesign.com
Description: provides a function to output RGB values from ACF colorpicker fields
Author: Peter Wise
Version: 0.1
Author URI: http://squarecandydesign.com
*/
/*
Example Usage:
h1 { color: rgb(<?php sqcdy_acf_rgb('my_colorpicker_field'); ?>); }
<?php $rgb = sqcdy_get_acf_rgb('my_colorpicker_option_field', 'option'); ?>
h2 { color: rgb(<?php echo $rgb ?>); }
div { background-color: rgba(<?php sqcdy_acf_rgb('my_colorpicker_field'); ?>,0.5); }
<?php echo 'h3 {color: rgba(' . sqcdy_get_acf_rgb('my_colorpicker_field') . ',0.5); }'; ?>
*/
// output an acf colorpicker field as R,G,B
function sqcdy_get_acf_rgb($field, $id) {
if ( function_exists('get_field') ) {
$hex = get_field($field, $id);
// extra sanity check that we're dealing with the hex colors
// in #NNNNNN format that ACF/WordPress/Iris colorpicker returns
if (strlen($hex) == 7 && substr($hex,0,1) == '#') {
$r = hexdec(substr($hex,1,2));
$g = hexdec(substr($hex,3,2));
$b = hexdec(substr($hex,5,2));
return $r . ',' . $g . ',' . $b;
}
else {
// provide a default in an emergency
return "128,128,128" ;
}
}
}
function sqcdy_acf_rgb($field, $id) {
echo sqcdy_get_acf_rgb($field, $id);
}
@petertwise
Copy link
Author

Nevermind - I see where the issue would come up from you code now. Maybe try keeping the conversion function separate from the ACF stuff like this:

function sqcdy_get_acf_rgb($hex) {
	// sanity check that we're dealing with the hex colors
	// in #NNNNNN format that ACF/WordPress/Iris colorpicker returns
	if (strlen($hex) == 7 && substr($hex,0,1) == '#') {
		$r = hexdec(substr($hex,1,2));
		$g = hexdec(substr($hex,3,2));
		$b = hexdec(substr($hex,5,2));
		return $r . ',' . $g . ',' . $b;
	}
	else {
		// provide a default in an emergency
		return "128,128,128" ;
	}
}

Then in your theme:

$myrepeater = get_field('my_repeater');
foreach ($myrepeater as $item) {
    $hex = $item['color_subfield'];
    $rgb = sqcdy_get_acf_rgb($hex);
    // do stuff with $rgb
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment