Draft Status Control for Sections in Bricks

Laurent Drapeau shared code in the Bricks Facebook group for quickly setting a Section in the Bricks editor as a “Draft” so it won’t be output in the frontend.

While the same can also be done using the Conditions feature, this method is a little more convenient.

Here’s a slightly improved version that ensures that there are no “Undefined array key” warnings.

Goes in child theme’s functions.php or a code snippets plugin.

// Add Section Status Control & Settings + Render
add_filter( 'bricks/elements/section/control_groups', function( $control_groups ) {
	$control_groups['draft_controls'] = [
		'tab' => 'content', // or 'style'
		'title' => esc_html__( 'Section Status', 'my_plugin' ),
	];

	return $control_groups;
} );

add_filter( 'bricks/elements/section/controls', function( $controls ) {
	$controls['draft_controls_active'] = [
		'tab' => 'content',
		'group' => 'draft_controls',
		'label' => esc_html__( 'Draft section', 'my_plugin' ),
		'type' => 'checkbox',
	];

	return $controls;
} );

add_filter( 'bricks/element/render', function( $render, $element ) {
	if ( $element->name === 'section' && isset( $element->settings["draft_controls_active"] ) && $element->settings["draft_controls_active"] == true ) {
		$render = false;
	}

	return $render;
}, 10, 2 );

Update: To add the control to all elements, use this code instead:

// Add Draft status control groups and control to all the elements.
add_action( 'init', function() {
	$elements = \Bricks\Elements::$elements;

	$names = array_keys( $elements );

	foreach( $names as $name ) {
		add_filter( "bricks/elements/{$name}/control_groups", 'bl_add_control_groups' );

		add_filter( "bricks/elements/{$name}/controls", 'bl_add_controls' );
	}
}, 30 );

function bl_add_control_groups( $control_groups ) {
	$control_groups['draft_controls'] = [
		'tab' => 'content',
		'title' => esc_html__( 'Set Draft Status', 'my_plugin' ),
	];

	return $control_groups;
}

function bl_add_controls( $controls ) {
	$controls['draft_controls_active'] = [
		'tab' => 'content',
		'group' => 'draft_controls',
		'label' => esc_html__( 'Draft status', 'my_plugin' ),
		'type' => 'checkbox',
	];

	return $controls;
}

add_filter( 'bricks/element/render', function( $render, $element ) {
	if ( isset( $element->settings["draft_controls_active"] ) && $element->settings["draft_controls_active"] == true ) {
		$render = false;
	}

	return $render;
}, 10, 2 );

References

https://academy.bricksbuilder.io/article/filter-bricks-elements-element_name-control_groups/

https://academy.bricksbuilder.io/article/filter-bricks-elements-element_name-controls/

https://academy.bricksbuilder.io/article/filter-bricks-element-render/

Step 3 of https://itchycode.com/create-my-custom-conditional-visibility-feature-in-bricks-theme-without-add-on/

Instant access to all 250+ Bricks code tutorials with BricksLabs Pro

2 comments

Leave your comment