Archived topic
How to use ACF Color Picker Field in Query Loop.
2 replies · Started by Martin on December 14, 2022
Hello! I just got a subscription to access the query loop block.
I have built this loop page with ACF data:
https://www.spelbladet.nu/casino/
But I can't set the CTA button backgrounds to an ACF Color Picker field. (field is called "logofarg").
TL;DR: I want the CTA background colors to be dynamic per item in the loop.
Many thanks!
Hi there,
CSS Styles in GB don't currently support dynamic data. Thats something we are working on.
To do it today is possible with a few steps and some code.
1. First we need to create a Global Color in Customizer > Colors.
Add a new color and give it a CSS variable name of dynamic
Set a color that will be used IF no ACF Color is set, treat it as the fallback color.
This variable name is important as we will be overwriting its value later on.
2. Edit your Query loop and select the Post Template Container Block inside it.
In Advanced > Additional CSS Class(es) add: dynamic-color
The classname is important as we will be using that to find the block using some PHP.
3. Set the Background color of that Container Block or any block within it to the dynamic color
4. Add this PHP Snippet to your site:
add_filter( 'render_block', function( $block_content, $block ) {
$field_name = 'your_acf_field_name'; // Set the name of the ACF field
$color = get_field( $field_name);
// If there is no color variable then exit
if ( empty($color) ) {
return $block_content;
}
$color_var = '--dynamic'; // CSS variable for color name
$class = 'dynamic-color'; // Additional CSS Class on block to find
$string = '<div'; // string of text to replace with date
if (
!is_admin()
&& ! empty( $block['attrs']['className'] )
&& $class === $block['attrs']['className']
) {
$replace = '<div style="' . $color_var . ': ' . $color . '" ';
$block_content = str_replace( $string , $replace , $block_content );
}
return $block_content;
}, 10, 2 );
Update the ACF field name in this line: $field_name = 'your_acf_field_name';
Worked great! Thank you