This code snippet enhances Bricks Builder by adding a “Custom Text” field to the control panel of selected elements (section, container, block, div). Users can enter any custom text, which will be automatically added as a data-custom-text attribute on the frontend HTML of these elements.
add_action( 'init', function () {
$targets = [ 'section', 'container', 'block', 'div' ];
foreach ( $targets as $name ) {
add_filter( "bricks/elements/{$name}/controls", function ( $controls ) {
$controls['custom_text'] = [
'tab' => 'content',
'label' => esc_html__( 'Custom Text', 'snn' ),
'type' => 'text',
'default' => '',
];
return $controls;
} );
}
} );
add_filter( 'bricks/frontend/render_element', function( $html, $element ) {
$targets = [ 'section', 'container', 'block', 'div' ];
$custom = $element->settings['custom_text'] ?? '';
if ( $custom !== '' && in_array( $element->name, $targets, true ) ) {
// Compose the Bricks-generated DOM ID
$dom_id = 'brxe-' . $element->id;
// Add data attribute directly to the root element.
// Use regex to safely inject after the id attribute (to avoid breaking class etc.)
$pattern = '/(<[^>]+id=["\']' . preg_quote($dom_id, '/') . '["\'])/i';
$replacement = '$1 data-custom-text="' . esc_attr($custom) . '"';
$html = preg_replace( $pattern, $replacement, $html, 1 );
}
return $html;
}, 20, 2 );