Archived topic
Add colored background to content template container based on meta value
5 replies · Started by Fergal on September 19, 2022
Hey there,
I'd like to add a colored background to posts that have a meta value of 1 for 'enhanced_listing' custom field. I've done the following which almost works, but it results in every container for the post having the class "my-enhanced-jo". Can you please help me fix this?
I've added class: "my-enhanced-bg" to the container containing a grid (please see imgur link)
Added this php:
add_filter( 'render_block', function( $block_content, $block ) {
if ( !is_admin() && ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'my-enhanced-bg' ) !== false ) {
$my_meta = get_post_meta(get_the_ID(), 'enhanced_listing', true);
if( $my_meta == 1) {
$my_new_class = 'my-enhanced-jo';
$myreplace1 = 'class="';
$myinsert1 = 'class=" ' . $my_new_class . ' ';
$block_content = str_replace( $myreplace1, $myinsert1 , $block_content );
}
}
return $block_content;
}, 10, 2 );
And using this CSS
CSS:
.my-enhanced-jo {
background: rgba(126,33,42,0.38);
}
Hi Fergal,
Can you provide the link to the page in question here as well?
Hey again Fernando,
Yes sorry I've provided it now as well as an image of a post where this is occurring.
Thanks!
Can you try this?:
add_filter( 'render_block', function( $block_content, $block ) {
if ( !is_admin() && ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'my-enhanced-bg' ) !== false ) {
$my_meta = get_post_meta(get_the_ID(), 'enhanced_listing', true);
if( $my_meta == 1) {
$my_new_class = 'my-enhanced-jo';
$myreplace1 = 'my-enhanced-bg';
$myinsert1 = $myreplace1 . ' ' . $my_new_class;
$block_content = str_replace( $myreplace1, $myinsert1 , $block_content );
}
}
return $block_content;
}, 10, 2 );
Worked perfectly thank you Fernando!
You're welcome Fergal!