- This topic has 7 replies, 2 voices, and was last updated 3 years, 4 months ago by
David.
-
AuthorPosts
-
December 12, 2022 at 4:54 am #2458824
David
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
DaveDecember 12, 2022 at 8:47 am #2459252David
StaffCustomer SupportHi 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 stylesor 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-styleclass.
ii. load$colorvariable withget_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-boxand adds the background color.December 12, 2022 at 9:09 am #2459302David
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…
December 12, 2022 at 10:02 am #2459386David
StaffCustomer SupportSo this line in the code:
$color = get_field('color');is where it gets the ACF field.
Did you change thecolorto the ACF Field name you’re using ?December 12, 2022 at 10:24 am #2459423David
I changed my field name to color in ACF, so it was the same
December 12, 2022 at 10:29 am #2459430David
StaffCustomer SupportHmm… did you re-add the color values in the actual post ? As if i recall, changing the name may lose whatever was originally set.
December 12, 2022 at 10:35 am #2459437David
That was it! thanks David, you absolute Legend 🙂
December 12, 2022 at 11:02 am #2459468David
StaffCustomer SupportAwesome – glad to hear that worked 🙂
-
AuthorPosts
- You must be logged in to reply to this topic.