Conditionally Excluding Elements from Bricks Editor

In the past, we shared How to Exclude Elements from Bricks Editor.

This Pro tutorial shows how specific elements can be excluded selectively based on the template/page being edited in Bricks builder.

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

/**
 * Exclude the specified elements from Bricks Builder on a specific template.
 */
add_filter( 'bricks/builder/elements', function( $elements ) {
	// current page request URI
	$request_uri = "$_SERVER[REQUEST_URI]";

	if ( strpos( $request_uri, 'single-product' ) !== false ) {
		$elements_to_exclude = [
			'text-basic',
			'facebook-page'
		];
	
		$elements = array_diff( $elements, $elements_to_exclude );
	}

	return $elements;
} );

where single-product is a slug in the Bricks editor page URL.

Ex.: at

https://bricks-2.local/template/single-product/?bricks=run

With the above code in place, Basic Text and Facebook Page elements will be removed from the add elements left panel when a Bricks Template having a title of “Single Product” is being edited.

strpos function in PHP can be used to check if a string contains another string. The strpos function returns the position of the first occurrence of a substring in a string, or false if the substring is not found.

Note the use of !== instead of != in the comparison. This is to ensure that the comparison returns false only if strpos returns false, and not if it returns 0, which is the position of the first character in the string.