Archived topic
Colour background on div in loop
7 replies · Started by David on December 12, 2022
Hello
I have a loop template loading on this page...
https://staging.inboxcreative.co.uk/websites/
On the posts I have a ACF added, which is a colour piker. I'm trying to change the background colour of the class website-box, based on the color that is selected on the post page.
I've tried adding this as a hook, showing in the footer, but it doesn't pick up the colour, any ideas how I can do this...
<style>
.website-box {
background: <?php the_field( 'colour' ); ?>;
background-color: #AED8C3;
}
</style>
Trying to replace the background color style.
Thanks
Dave
Hi there,
its a bit more complicated then that, as the styles would need to be injected for each post.
One option would be:
1. Edit the Query Loop, inside its post template, add another Headline Block.
1.1 Give it some static text eg. placeholder for styles or whatever you want.
1.2 In Advanced > Additional CSS Class(es) add: inline-style
2. Publish those changes.
3. Now add this PHP snippet to your site:
add_filter( 'render_block', function( $block_content, $block ) {
if (
!is_admin()
&& ! empty( $block['attrs']['className'] )
&& 'inline-style' === $block['attrs']['className']
) {
$color = get_field('color');
if ( empty($color) ) {
$color = '#ff0000';
}
$block_content = sprintf('<style>.post-%1$s .website-box {background-color: %2$s;}</style>',
get_the_ID(),
$color
);
}
return $block_content;
}, 10, 2 );
This will:
i. Look for the block with the inline-style class.
ii. load $color variable with get_field('color') - update the get_field to include your ACF field name.
iii. swap the HTML for a Style tag that targets the .post-{id} .website-box and adds the background color.
Thanks David, that nearly did it, but it's not picking up the color that is selecting in the picker. Just showing the fallback empty color...
So this line in the code: $color = get_field('color'); is where it gets the ACF field.
Did you change the color to the ACF Field name you're using ?
I changed my field name to color in ACF, so it was the same
Hmm... did you re-add the color values in the actual post ? As if i recall, changing the name may lose whatever was originally set.
That was it! thanks David, you absolute Legend :)
Awesome - glad to hear that worked :)