Get 30% discount on lifetime membership by using BFCM2023 coupon.
Offer ends on 30th Nov 2023 at 11:59:59 PM UTC.

Render an element having a specific HTML ID based on value of a custom field

This tutorial provides the steps to use Bricksbricks/element/render filter to conditionally output an element that has the specified HTML ID based on the value of a specific custom field of the current post when viewing a singular page.

In this example, we shall use ACF to create a field group attached to Pages that has a single True / False type of field – hide_footer_cta and set a Section whose HTML ID is footer-cta to be output only on Pages for which that field has been set to false.

Creating the custom field
Entering HTML ID for an element in Bricks builder
Populating the custom field

When Hide Footer CTA has been turned on i.e., set to Yes, the Section should not be rendered.

Here’s the code for this to be added in child theme’s functions.php or a code snippets plugin like WPCodeBox:

// Render an element with "footer-cta" HTML ID if the specified condition is true.
// Condition: The value of a custom field "hide_footer_cta" is false.
add_filter( 'bricks/element/render', function( $render, $element ) {	
	// Get the element HTML ID
	$html_id = ! empty( $element->attributes['_root']['id'] ) ? $element->attributes['_root']['id'] : false;

	if ( 'footer-cta' === $html_id ) {
		return ! get_post_meta( $element->post_id, 'hide_footer_cta', true );
	}

	return $render;
}, 10, 2 );
Instant access to all 250+ Bricks code tutorials with BricksLabs Pro

2 comments

  • Thanks! How to do the exact opposite? Hide an element targeted by html ID, if the hide_footer_cta is FALSE.

    Can you update this article with that? ๐Ÿ™‚

    Thank you in advance!

    • Sorry, that's not what I meant... I meant hide an element if the value is true, instead of displaying it.

Leave your comment