Skip to content
Arrow keys to move, Enter to open, Esc to closeAll results
Design and Builders · Guides

How to Build a Custom Element for Bricks Builder With PHP

Build a Bricks Builder custom element in PHP: class, controls, safe output, assets that load only when used, registration and testing, with a full callout example.

Written by
WPresident Editorial
Topic
Design and Builders

Sooner or later a Bricks site needs a piece of interface that the built-in elements do not quite cover. A callout box with four variants. A pricing row that reads from a custom field and refuses to print an empty price. A rating display that needs a little server-side logic and a small script that must not load on pages that do not use it. You can fake these with a container, a few classes and a Code element, and for a one-off page that is often the right call. But when the same piece appears across dozens of pages, built by several people, the faked version drifts: someone changes a class, someone pastes a different heading tag, someone forgets the accessibility attribute. A custom element fixes that by moving the decisions into code, and giving editors a small set of controls that cannot produce a broken result.

The single most important idea in this guide is that a custom element is one PHP class doing two jobs for two audiences. For the builder, it describes itself: a name, a category, an icon, a label and a list of controls. For the front end, it prints HTML from whatever values the editor chose. Everything else follows from keeping those jobs separate and honest. The control definitions are a contract with the editor, so they should offer only valid choices. The render method is a contract with the visitor, so it must treat every stored value as untrusted, escape it, and tolerate missing values without a PHP notice.

This guide builds one complete, minimal element, a callout with a title, some text and a variant control, and uses it to explain each part. It starts with when a custom element is the right tool compared with global classes, components and the Code element. It then shows the anatomy of an element class, gives the whole callout in three small files (a plugin file, the element class and a stylesheet), and goes through the pieces: the name, category and icon; the controls and how they map to styles; the render method and the escaping it needs; assets that load only on pages where the element appears; registration and where the files should live; how builder rendering differs from front-end rendering; optional JavaScript; a testing checklist; and a troubleshooting list.

A few honest boundaries. This is a general guide, not a test report, and it was written from the public Bricks documentation. Class names, method names, properties and hooks used here are the ones the documentation describes, and where the documentation is thin or a community answer contradicts it, the text says so and tells you what to verify. Bricks changes over time, so read the current developer pages on creating elements and on controls before you commit to a design, and test on a staging copy. The code samples are written to be readable and correct, but you remain responsible for running them through your own review before they touch a production site.

You need working PHP knowledge: classes, arrays, and the WordPress functions for escaping output. You do not need to know the internals of Bricks. You need a staging site with Bricks active, a place to put code that is not the parent theme, and the habit of reading the browser’s network and console panels when something does not appear. If you can write a WordPress shortcode safely, you can write a Bricks element; the new part is the controls, and that part is mostly a list of arrays.

Key points

  • A custom element is one PHP class with two jobs: describe the element and its controls to the builder, and render safe HTML on the front end.
  • Extend the Bricks element class, set a prefixed name, a category and an icon, define controls in set_controls, and print the root attributes in render so classes, IDs and style-tab CSS reach the markup.
  • Treat every saved setting as untrusted: validate choices against the same list the control offers, escape text, and allow only safe HTML for rich text.
  • Use the element’s enqueue method for its own styles and scripts so they load only on pages where the element is used.
  • Register elements on init after the theme has loaded, from a small site plugin or the child theme, never by editing the parent theme.
  • Test the element in the builder and on the front end, with empty values, hostile text, dynamic data, copy and paste, and debug logging on.

When a custom element is the right tool

Bricks gives you several ways to reuse a piece of design, and a custom element is the heaviest. Choose it on purpose, after ruling out the lighter options.

A global class reuses styles. If the problem is that five headings should look the same, a class does it, with no code. A component reuses a group of elements with editable parts, which the Bricks documentation describes as reusable element groups with variable slots and nesting. If the problem is that a card made of an image, a heading and a button appears everywhere with different content, a component keeps the structure in one place. A template reuses a whole section or page region and can be placed by conditions. These three need no PHP, no deployment and no code review, which is a strong argument for using them first.

The Code element lets you place PHP, HTML, CSS or JavaScript at a specific point in the output. The Bricks documentation treats executable code as security sensitive: it runs only when code execution is switched on, the user has the execute-code capability and the saved code carries a valid signature. That makes it fine for a controlled one-off, and a poor home for logic that many editors depend on, because the code lives in page data rather than in version control, and it is signed and re-signed through the builder.

A custom element is the right tool when at least one of these is true. You need your own controls with a restricted set of choices, so editors cannot produce an invalid state. You need server-side logic that components cannot express, such as reading and formatting a value, calling a function, or choosing markup from a setting. You need output that is validated and escaped in one place. You need the element’s CSS or JavaScript to load only where the element is used. Or you want the element to live in version control and ship with a plugin, so it is reviewed, deployed and rolled back like any other code.

It also helps to be clear about the cost. A custom element is code you own. When Bricks changes how elements are rendered or styled, you are the one who finds out whether it still works, which is why the testing section later in this guide matters. It must be loaded on every environment where a page uses it: if you deactivate the plugin that registers the element, pages that contain it show nothing or an error placeholder where the element used to be. And every control you add is a decision that editors must understand, so add only what the design needs.

A quick test: describe the thing in one sentence that starts with the editor can choose. If the sentence ends in a list of values (info, success, warning, danger), a custom element is a good fit. If it ends in anything at all, a global class or a component is probably enough.

What do you need to reuse?

What is the thing you keep rebuilding?
The same styles on different elementsGlobal class: no code, no deployment.
The same group of elements with editable partsComponent or template: structure reuse without PHP.
One piece of PHP output at one point in one pageCode element, only with code execution enabled and signed code, and ideally not for shared logic.
Controlled choices, server-side logic, validated output or conditional assetsCustom element in a plugin or child theme.
A starting rule for choosing between a class, a component, a template, the Code element and a custom element.

The anatomy of an element class

The Bricks documentation describes creating an element as following a pattern similar to creating a WordPress widget. You write a class that extends the Bricks element class, set a few properties, and fill in the methods the builder and the front end call. The class is \Bricks\Element, and everything below is what the developer documentation lists for it.

There are six properties. $category is required and is the group in the elements panel: use one of the predefined categories such as general or media, or your own lowercase name with no spaces, in which case you also supply a translatable label with a builder filter. $name is required, a unique lowercase identifier, and the documentation tells you to prefix it to avoid conflicts. $icon is an icon font class from the icon fonts Bricks bundles. $css_selector sets where the CSS controls apply by default, and the next sections explain why it is the source of a common confusion. $scripts lists JavaScript function names that run for the element, and $nestable turns the element into one that can contain other elements.

The methods split into two groups, and the documentation labels them as builder-specific and front-end-specific. Builder-specific methods describe the element: get_label() returns the localised name shown in the panel and is required; get_keywords() returns an array of strings that make the element appear when someone searches the panel; set_control_groups() defines groups that organise the controls into collapsible sections; and set_controls() defines the controls themselves and is required. Front-end-specific methods produce the output: enqueue_scripts() loads the element’s scripts and styles, and the documentation says they load only on pages where the element is used; render() prints the HTML and is required.

Inside render() you have helpers. set_attribute( $key, $attribute, $value ) records an HTML attribute against a key of your choosing, and render_attributes( $key ) prints the attributes recorded for that key. The special key _root holds the attributes Bricks itself needs on the outermost tag, such as the element ID and classes; the documentation comment next to it says the attribute is required, so always print it on your outermost tag. Two more helpers handle dynamic data: render_dynamic_data( $content ) for a string that may contain tags such as the post title, and render_dynamic_data_tag( $tag, $context, $args ) for a single tag. The documentation says they set the correct post ID for the environment where the element is rendering. Finally, every setting the editor chose arrives in $this->settings, an array keyed by your control IDs, and the documentation suggests printing it with var_dump inside render() while you are learning what is stored.

The figure shows the order in which Bricks learns about and uses the class, which explains most “my element does not appear” problems: if any step before the last one fails, the element never reaches the page.

How an element gets from your file to the page

  1. WordPress loads the theme and pluginsThe Bricks classes exist once the Bricks theme is active.
  2. Your code runs on initA callback registers each element file after the theme has loaded.
  3. register_element loads the classBricks includes your PHP file and learns the element name and class.
  4. The builder reads the classLabel, category, icon, keywords and controls build the panel entry and the settings UI.
  5. The editor saves settingsValues are stored on the page, keyed by your control IDs.
  6. render prints the HTMLOn the front end and in the canvas, the same method turns settings into markup.
The loading order for a custom element: nothing reaches the builder or the front end unless the registration step runs.

The complete callout element in three files

Here is the whole example, small enough to read in one sitting. The callout has a title, a rich text body, a variant (info, success, warning or danger), a heading tag choice, and two style controls. It lives in a small site plugin with three files: the plugin file that registers the element, the element class and a stylesheet. The rest of this guide explains the decisions in them, so read the code once now and again after each section.

The first file is the plugin entry point, wpr-bricks-elements.php. It defines two constants, registers the element on init and provides the translatable category label.

<?php
/**
 * Plugin Name: WPR Bricks Elements
 * Description: Custom Bricks elements for this site.
 * Version: 1.0.0
 * Requires PHP: 7.4
 * Text Domain: wpr-bricks
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

define( 'WPR_BRICKS_DIR', plugin_dir_path( __FILE__ ) );
define( 'WPR_BRICKS_URL', plugin_dir_url( __FILE__ ) );

add_action( 'init', function () {
	// Do nothing when the Bricks theme is not active.
	if ( ! class_exists( 'Bricks\Elements' ) ) {
		return;
	}

	\Bricks\Elements::register_element(
		WPR_BRICKS_DIR . 'elements/callout.php',
		'wpr-callout',
		'WPR_Element_Callout'
	);
}, 11 );

add_filter( 'bricks/builder/i18n', function ( $i18n ) {
	$i18n['wpr'] = esc_html__( 'WPR elements', 'wpr-bricks' );
	return $i18n;
} );

The second file, elements/callout.php, is the element itself.

<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class WPR_Element_Callout extends \Bricks\Element {
	public $category = 'wpr';
	public $name     = 'wpr-callout';
	public $icon     = 'fas fa-circle-info';
	public $nestable = false;

	// One list feeds both the control and the validation in render().
	private function wpr_variants() {
		return [
			'info'    => esc_html__( 'Info', 'wpr-bricks' ),
			'success' => esc_html__( 'Success', 'wpr-bricks' ),
			'warning' => esc_html__( 'Warning', 'wpr-bricks' ),
			'danger'  => esc_html__( 'Danger', 'wpr-bricks' ),
		];
	}

	public function get_label() {
		return esc_html__( 'Callout', 'wpr-bricks' );
	}

	public function get_keywords() {
		return [ 'callout', 'notice', 'note', 'alert', 'tip' ];
	}

	public function set_control_groups() {
		$this->control_groups['text'] = [
			'title' => esc_html__( 'Text', 'wpr-bricks' ),
			'tab'   => 'content',
		];
		$this->control_groups['look'] = [
			'title' => esc_html__( 'Callout look', 'wpr-bricks' ),
			'tab'   => 'style',
		];
	}

	public function set_controls() {
		$this->controls['title'] = [
			'tab'     => 'content',
			'group'   => 'text',
			'label'   => esc_html__( 'Title', 'wpr-bricks' ),
			'type'    => 'text',
			'default' => esc_html__( 'Good to know', 'wpr-bricks' ),
		];

		$this->controls['text'] = [
			'tab'     => 'content',
			'group'   => 'text',
			'label'   => esc_html__( 'Text', 'wpr-bricks' ),
			'type'    => 'editor',
			'default' => esc_html__( 'Write the note here.', 'wpr-bricks' ),
		];

		$this->controls['variant'] = [
			'tab'         => 'content',
			'group'       => 'text',
			'label'       => esc_html__( 'Variant', 'wpr-bricks' ),
			'type'        => 'select',
			'options'     => $this->wpr_variants(),
			'inline'      => true,
			'clearable'   => false,
			'pasteStyles' => false,
			'default'     => 'info',
		];

		$this->controls['titleTag'] = [
			'tab'         => 'content',
			'group'       => 'text',
			'label'       => esc_html__( 'Title tag', 'wpr-bricks' ),
			'type'        => 'select',
			'options'     => [
				'h2' => 'H2',
				'h3' => 'H3',
				'h4' => 'H4',
				'h5' => 'H5',
				'h6' => 'H6',
			],
			'inline'      => true,
			'clearable'   => false,
			'pasteStyles' => false,
			'default'     => 'h3',
		];

		$this->controls['titleTypography'] = [
			'tab'    => 'style',
			'group'  => 'look',
			'label'  => esc_html__( 'Title typography', 'wpr-bricks' ),
			'type'   => 'typography',
			'inline' => true,
			'css'    => [
				[
					'property' => 'typography',
					'selector' => '.wpr-callout__title',
				],
			],
		];

		$this->controls['boxBackground'] = [
			'tab'    => 'style',
			'group'  => 'look',
			'label'  => esc_html__( 'Background', 'wpr-bricks' ),
			'type'   => 'color',
			'inline' => true,
			'css'    => [
				[
					'property' => 'background-color',
					'selector' => '.wpr-callout__box',
				],
			],
		];
	}

	public function enqueue_scripts() {
		wp_enqueue_style(
			'wpr-callout',
			WPR_BRICKS_URL . 'assets/callout.css',
			[],
			filemtime( WPR_BRICKS_DIR . 'assets/callout.css' )
		);
	}

	public function render() {
		$settings = $this->settings;

		$variant = isset( $settings['variant'] ) ? $settings['variant'] : 'info';
		if ( ! array_key_exists( $variant, $this->wpr_variants() ) ) {
			$variant = 'info';
		}

		$tag = isset( $settings['titleTag'] ) ? $settings['titleTag'] : 'h3';
		if ( ! in_array( $tag, [ 'h2', 'h3', 'h4', 'h5', 'h6' ], true ) ) {
			$tag = 'h3';
		}

		$title = isset( $settings['title'] ) ? $this->render_dynamic_data( $settings['title'] ) : '';
		$text  = isset( $settings['text'] ) ? $this->render_dynamic_data( $settings['text'] ) : '';

		if ( '' === trim( $title ) && '' === trim( wp_strip_all_tags( $text ) ) ) {
			// Print nothing for visitors; give editors a visible hint in the builder.
			if ( bricks_is_frontend() ) {
				return;
			}
			$title = esc_html__( 'Callout: add a title or text', 'wpr-bricks' );
		}

		$this->set_attribute( '_root', 'class', [ 'wpr-callout', 'wpr-callout--' . $variant ] );
		$this->set_attribute( 'box', 'class', 'wpr-callout__box' );
		$this->set_attribute( 'box', 'role', 'note' );

		echo '<div ' . $this->render_attributes( '_root' ) . '>';
		echo '<div ' . $this->render_attributes( 'box' ) . '>';

		if ( '' !== trim( $title ) ) {
			printf(
				'<%1$s class="wpr-callout__title">%2$s</%1$s>',
				tag_escape( $tag ),
				esc_html( $title )
			);
		}

		if ( '' !== trim( $text ) ) {
			echo '<div class="wpr-callout__text">' . wp_kses_post( $text ) . '</div>';
		}

		echo '</div></div>';
	}
}

The third file, assets/callout.css, styles the output with custom properties so each variant only changes a few values.

.wpr-callout {
  --wpr-callout-accent: #1d4ed8;
  --wpr-callout-bg: #eff6ff;
}
.wpr-callout--success {
  --wpr-callout-accent: #15803d;
  --wpr-callout-bg: #f0fdf4;
}
.wpr-callout--warning {
  --wpr-callout-accent: #a16207;
  --wpr-callout-bg: #fefce8;
}
.wpr-callout--danger {
  --wpr-callout-accent: #b91c1c;
  --wpr-callout-bg: #fef2f2;
}

.wpr-callout__box {
  background: var(--wpr-callout-bg);
  border-left: 4px solid var(--wpr-callout-accent);
  border-radius: 4px;
  color: #1f2937;
  padding: 1rem 1.25rem;
}
.wpr-callout__title {
  color: var(--wpr-callout-accent);
  font-size: 1.1rem;
  margin: 0 0 0.35rem;
}
.wpr-callout__text > :last-child {
  margin-bottom: 0;
}

The folder layout is wpr-bricks-elements/wpr-bricks-elements.php, wpr-bricks-elements/elements/callout.php and wpr-bricks-elements/assets/callout.css. The sections that follow take the pieces apart in turn.

Name, category, icon and keywords

The four identity properties look trivial, and they are the part you cannot change freely later, because pages that use your element store its name. Treat them like a public API.

The name is the unique identifier, lowercase with no spaces, and the Bricks documentation tells you to prefix it. The example uses wpr-callout: wpr is the vendor prefix, callout the thing. A prefix protects you from a collision with a future built-in element or another plugin’s element of the same name. Once a page has been saved with the element on it, that page refers to it by this name, so renaming the property later leaves existing pages pointing at an element that no longer exists. Choose the name once. The same logic applies to control IDs: the values the editor saves are keyed by them, so renaming a control orphans the saved values. If you must change one, plan a migration, and do it on staging.

The category decides where the element appears in the elements panel. The documentation says to use one of the predefined categories, such as general or media, or to assign your own lowercase name with no spaces. A custom category needs a translatable string, supplied through the bricks/builder/i18n filter, with the category name as the array key and the label as the value. That is the last block in the plugin file: $i18n['wpr'] = esc_html__( 'WPR elements', 'wpr-bricks' );. Create one custom category for all your elements rather than one per element, so editors learn where to look. If you only have one or two elements, the predefined general category is perfectly reasonable and removes a filter you would otherwise maintain.

The icon is an icon font class. The documentation lists the fonts Bricks bundles: Font Awesome 6, Ionicons 4 and Themify Icons, with example classes in each style. The callout uses a Font Awesome 6 solid icon, fas fa-circle-info. If the icon does not show in the panel, the usual cause is a class name from a different icon set or version than the one Bricks bundles, so check the class against the icon set’s own list. The icon is for editors only; it does not appear on the front end.

The label and keywords are the editor’s way to find the element. get_label() returns a localised string, and you should always route it through a translation function with your own text domain so the panel works in the editor’s language. get_keywords() returns an array of strings that make the element appear when someone searches the panel, and the best keywords are the words editors already use for the thing, not its official name. A callout is also called a notice, a note, an alert, a tip or an admonition, so those go in the list. Keep keywords lowercase and few, since a long list makes the element appear for searches it should not.

Two smaller conventions are worth adopting. Give the PHP class a prefixed name, such as WPR_Element_Callout, so it cannot collide with another class in the global namespace. And put one element in one file, named after the element, so the registration list reads like a table of contents and a change to one element never touches another.

Controls: what the editor can choose and how it becomes CSS

Controls are where a custom element earns its keep. Each control is an entry in the $this->controls array, keyed by an ID that becomes the key in $this->settings. The Bricks documentation lists the arguments every control accepts: tab (content or style), group, label, type, inline, small, css, default, pasteStyles, description and required. Each control type then adds its own arguments, and the developer documentation has a page per type.

Look at the callout’s controls. The title is a text control and the body an editor control, which gives editors a small rich text field. The variant is a select with the options defined once in a helper method. The title tag is another select limited to H2 through H6, because the right heading level depends on where the callout sits in the page outline and a free text field would invite invalid tags. Both selects set clearable to false so editors cannot empty them, inline to show the label and input on one line, and pasteStyles to false. The documentation recommends this for controls that output HTML content instead of CSS, and its own examples set the argument to false for them, which keeps them out of the builder’s paste styles action, so pasting the styles of a danger callout onto an info callout does not silently change its meaning.

Notice the principle: a select with named options is a safer control than a text field, because the set of possible values is closed. That is what lets render() trust the value after a one-line check. A free text field for the variant would force you to validate and would let typos through.

The css argument turns a control into a style rule. It is an array of rule definitions, each needing a property and a selector. The documentation example sets a colour control’s property to color and its selector to a class inside the element. The callout’s typography control uses the property typography with the selector .wpr-callout__title, and the background control uses background-color with .wpr-callout__box. At build time Bricks writes a CSS rule for the element’s unique ID and your selector, so the style applies only to that instance of the element. A practical consequence is that style-tab values override your stylesheet’s class rules, which is what you want: the stylesheet provides the default look and the editor’s choice wins. The second figure at the end of this section shows that override.

Now the common trap. The documentation lists a $css_selector property, described as the default selector for CSS controls, and it is often set by people copying the sample class. Forum answers show that it is the usual reason the style tab seems dead: Bricks applies the built-in style controls to the root element, and if you set $css_selector to a class that no element in your markup carries, the generated rules match nothing. The same threads report that a custom class added in the style tab disappears from the front end when the root tag does not print its attributes. The fix for both is simple: omit $css_selector unless you have a child element that should receive the default styles, and always print render_attributes( '_root' ) on the outermost tag.

Conditional controls use the required argument: an array holding a control ID, a comparison operator and a value. For example, 'required' => ['variant', '=', 'custom'] shows a control only when the variant select is set to custom. The documentation pairs this with an info control, which shows a hint in the panel and outputs nothing on the front end. Use conditionals to hide advanced options, not to hide required ones.

Finally, do not assume that a control’s default value is present in $this->settings when the editor never touched the control. Give render() its own fallback for every value, as the callout does with isset checks and a fallback variant. The element then works whether or not Bricks passes the default.

// An optional link, added to set_controls().
$this->controls['link'] = [
	'tab'         => 'content',
	'group'       => 'text',
	'label'       => esc_html__( 'Link', 'wpr-bricks' ),
	'type'        => 'link',
	'pasteStyles' => false,
];

// In render(), after the text block.
if ( ! empty( $settings['link'] ) ) {
	$this->set_link_attributes( 'a', $settings['link'] );
	echo '<a ' . $this->render_attributes( 'a' ) . '>' . esc_html__( 'Read more', 'wpr-bricks' ) . '</a>';
}

The link control stores a structured value (target page or URL, new tab and rel options), and the documentation shows set_link_attributes turning it into attributes for a key of your choice, printed with render_attributes. That keeps URL handling inside Bricks. The visible text is fixed here; a second text control would make it editable. The first figure below shows both versions.

Rendered output of the code above
Two warning callouts. The first has a title, a line of text and a Read more link under the text. The second has the same content but its link reads Read the staging checklist, with a note that descriptive link text works better when a page has several callouts.
A plain HTML and CSS render of the callout with the optional link, once with the fixed Read more text and once with editable descriptive text; not a screenshot of the Bricks editor.
Rendered output of the code above
Two info callouts. The first has the default pale blue background and a normal-size title from the stylesheet. The second has a pale orange background and a larger, upper-case title, as if the editor had set a background colour and title typography in the style tab.
A plain HTML and CSS render of why style-tab values win: an ID-scoped rule, standing in for the rule Bricks generates, overrides the class rules from the stylesheet; not a screenshot of the Bricks editor.

The render method and the escaping it needs

Render is where security lives. Everything in $this->settings was typed or chosen by a person with access to the builder, and everything resolved from dynamic data came from the database. Neither is trustworthy markup. The Bricks documentation’s own control examples echo settings directly to keep the examples short, and that is fine for learning but not for production. In your element, validate what can be validated, escape the rest, and allow HTML only where the design needs it.

Walk through the callout’s render() in order.

Read and validate choices. The variant is read from settings with a fallback, then checked against the same options array the control uses, with array_key_exists. If someone pasted data from another site, or a future edit left a value that no longer exists, the element degrades to info instead of printing a class from untrusted data. The tag is checked with in_array and strict comparison against the five allowed heading tags, so the value that reaches printf is always one of five known strings, and tag_escape is a second layer of defence.

Resolve dynamic data, then escape. Both text values go through $this->render_dynamic_data(), the helper the documentation describes for strings that may contain tags such as the post title. It matters that this comes first and the escaping second: after the tags are resolved, the string can hold whatever the post title or custom field contains, including markup, and the escape function must see that final string. The title is then printed with esc_html and the body with wp_kses_post, which keeps the formatting a rich text editor produces and removes scripts, event attributes and other markup that has no place in post content.

Handle emptiness. If both values are empty, a visitor should see nothing, not an empty tinted box with an accent border. The early return on bricks_is_frontend(), the helper documented to tell front-end rendering from builder rendering, does that. In the builder the same case shows a hint, so editors see a placeholder instead of an invisible element they cannot click.

Print the root. set_attribute( '_root', 'class', [...] ) adds your classes to the root’s attributes, which Bricks fills with the element ID and any classes the editor added in the style tab. A second key, box, carries the class and a role of note for the inner wrapper. Both are printed with render_attributes, which returns the finished attribute string.

Print the tag safely. The heading is built with printf and positional placeholders so the tag name appears in both opening and closing tags, escaped by tag_escape, with the text in esc_html. Never concatenate an unvalidated tag name into markup.

A few more habits belong here. Do not run heavy queries or remote requests inside render() without caching, because the builder renders elements repeatedly as you edit, and a slow render makes editing feel broken. Do not echo before the root opens, as stray output breaks the structure Bricks expects. And remember that a rendering error on one element should not take the page down: guard calls to functions from other plugins with function_exists.

Which escaping function for which value

UseWhy
Plain text such as a titleesc_htmlTurns markup characters into text
Rich text from an editor controlwp_kses_postKeeps normal post HTML, removes scripts and event attributes
An attribute valueesc_attrSafe inside quotes in a tag
A URLesc_urlRejects unsafe schemes and escapes the address
A tag name from a selectin_array check, then tag_escapeThe value must be one of a closed list
A CSS class token from a settingsanitize_html_class or a whitelistPrevents breaking out of the class attribute
Pick the function by where the value is printed and what it is allowed to contain, and apply it at the moment of output.

Styles and scripts that load only when the element is used

The easiest way to make a site slower is to ship every element’s CSS and JavaScript on every page. Bricks avoids it for its own elements: the developer documentation on asset loading says the main stylesheet and script always load while sliders, lightboxes, maps and the like are registered and loaded only when needed. Your element should follow the same rule, and the framework gives you the hook for it.

The enqueue_scripts() method on the element class is where you enqueue the element’s own assets. The documentation states that what you enqueue there is loaded only on pages where the element is used. That is the whole mechanism, and it is why the callout’s stylesheet is enqueued inside the element rather than in a global wp_enqueue_scripts callback in the plugin file. A page without a callout never requests callout.css.

Inside the method use the standard WordPress functions: wp_enqueue_style with a handle, a URL built from the plugin’s URL constant, a dependency array and a version, and wp_enqueue_script for scripts, with the final argument true to load them in the footer. The callout passes filemtime of the stylesheet as the version, so browsers fetch a new copy whenever the file changes. Use a handle prefixed with your vendor name, because handles share one global namespace with every plugin and theme.

If you want your stylesheet to arrive in a predictable order relative to Bricks’ own CSS, name bricks-frontend as a dependency, which the Bricks child theme guide uses for exactly that purpose. The element’s selectors are all prefixed with wpr-callout, so conflicts with theme styles are unlikely, and custom properties let the variants differ by four values instead of four copies of every rule.

Keep the CSS small and independent of the builder. A few rules apply to almost any element: scope every selector under your own class, never target bare tags such as p or h3 globally, use logical colours with enough contrast for the text on them, and let the style tab override the defaults, which is what the css arguments on the controls arrange. The figure shows the four variants rendered from the stylesheet above. It is a plain HTML and CSS render of the technique, drawn by a browser, and not a screenshot of the Bricks editor or of an actual element on a page.

One structural decision remains: how much to put in the stylesheet and how much in controls. Put structure, spacing and variant colours in the stylesheet, where a developer can review them as code. Offer controls only for what editors genuinely vary: typography, background and spacing of a given instance. Too many controls produce inconsistent pages; too few send editors back to custom CSS, which defeats the purpose of the element. The callout offers two style controls on top of the four variants, which is a reasonable starting point.

Rendered output of the code above
Four stacked callout boxes with a coloured left border and a tinted background: a blue Info callout, a green Success callout, a yellow Warning callout and a red Danger callout, each with a bold title and one line of text.
A plain HTML and CSS render of the four callout variants from the stylesheet in this guide, not a screenshot of the Bricks editor.

Registering the element and choosing where the files live

A class that is never registered does nothing. The Bricks documentation shows the registration inside an init callback with a priority of 11, calling \Bricks\Elements::register_element() for each element file. The method takes up to three arguments: the full server path to the element file, which is required; the element name, as in wpr-callout; and the class name, as in WPR_Element_Callout. The two optional arguments are worth supplying, because the documentation says they improve loading performance, presumably because Bricks then knows what the file contains without having to inspect it. Keep the name and class identical to the properties inside the file; a mismatch is a quiet way to get an element that registers but never renders.

With more than one element, loop over a list so the plugin file stays short.

add_action( 'init', function () {
	if ( ! class_exists( 'Bricks\Elements' ) ) {
		return;
	}

	$elements = [
		'callout' => 'WPR_Element_Callout',
		'rating'  => 'WPR_Element_Rating',
	];

	foreach ( $elements as $slug => $class ) {
		$file = WPR_BRICKS_DIR . 'elements/' . $slug . '.php';

		if ( is_readable( $file ) ) {
			\Bricks\Elements::register_element( $file, 'wpr-' . $slug, $class );
		}
	}
}, 11 );

The guard on class_exists means the plugin does nothing when another theme is active, instead of causing a fatal error in a file that extends a class that does not exist. The is_readable check turns a typo in the list into a missing element instead of a fatal error. Adding a new element is then one line in the array and one new file.

Where should the code live? The documentation’s own example puts the element file in the root of the Bricks child theme and registers it from the child theme’s functions.php. That is a valid home for a small site. A site plugin is the better home for anything you want to keep when the design changes, move to another site, or switch off to debug. The Bricks best-practices page is blunt about the one place that is never acceptable: do not edit the Bricks theme files directly, because an update overwrites the changes; use a child theme or a code snippets plugin for custom code. A snippets plugin suits short filters, though an element class with its own stylesheet fits a file layout better than a database-stored snippet. A companion WPresident guide covers the child theme and code setup in more detail.

Whichever home you choose, keep the code under version control, deploy it through staging, and give it a real version number so you can tell what is running where. If the elements are part of how the site works rather than how it looks, they belong in a plugin. If they are purely presentation tied to one design, the child theme is simpler.

Child theme or site plugin for custom elements

Child themeSite plugin
Used in the Bricks documentation exampleYes, element file in the child theme rootNot shown, but the same registration code works
Survives a Bricks updateYes, it is separate from the parent themeYes
Reuse on another siteCopy files out of the themeInstall the same plugin
Switch off to debugSwitch themes, which changes the whole siteDeactivate one plugin
Best forSmall, design-specific elementsShared or functional elements, several sites
Both are valid homes for element code; the difference is what happens when the design, the host or the site changes.

Builder rendering versus front-end rendering

A custom element lives in two environments, and most surprises come from forgetting that. On the front end a visitor requests a page, WordPress loads Bricks, Bricks walks the saved element data and calls your render() for each instance, and the browser receives the HTML plus the CSS and JavaScript you enqueued. In the builder, the editor changes a control, and the canvas must show the result without a page reload. For a PHP element the canvas needs HTML from somewhere, and the same render() method produces it. You can confirm what happens on your version by watching the network panel while you edit a control.

The practical rule is that render() must work in both places and must know which place it is in. Bricks documents helper functions for this: bricks_is_frontend() tells you the element is rendering on the front end rather than in the builder, and the render-element filter documentation shows three more checks, bricks_is_builder_main(), bricks_is_builder_iframe() and bricks_is_builder_call(), for the builder interface, the canvas and a builder-triggered request. The callout uses the first: an empty callout prints nothing for visitors and a hint in the builder, as the second figure below shows.

Use the distinction for four things. First, for placeholders and hints, as above, because an element with no visible output cannot be clicked in the canvas. Second, to skip anything that should only happen for visitors, such as tracking attributes. Third, to avoid loading styles in the builder panel itself: the Bricks child theme guide warns that custom CSS can affect the builder interface, and shows a check on bricks_is_builder_main() before enqueueing a global stylesheet. Your element’s own CSS is scoped under a prefix, so this matters less for it. Fourth, to keep builder renders cheap: the canvas may re-render the element on every control change, so a render that queries the database or calls a remote API will make editing sluggish.

Remember too that your element’s output is not necessarily final. Bricks documents filters that run around element rendering: bricks/element/settings can change an element’s settings before they are used, bricks/element/render_attributes can add attributes to the nodes the element renders, and bricks/frontend/render_element can rewrite an element’s finished HTML on the front end. Site code or other plugins can use them, and some of them may reach your element. If a custom element renders correctly in isolation and oddly on a particular site, search that site’s code for these hooks before debugging your own.

The data sits in layers underneath all of this. The saved settings are the single source of truth; the control definitions say which settings can exist; the registration decides whether the element exists at all. If the layer at the bottom fails, every layer above it fails too, which is why the debugging order in the troubleshooting section starts at the bottom of the figure.

Layers of a custom element, from registration to the visitor

Front end and canvasHTML from render(), plus CSS and JavaScript enqueued only where the element is used.
Saved settingsValues the editor chose, stored on the page and keyed by control ID.
Builder panelControls from set_controls and set_control_groups, searchable by label and keywords.
The element className, category, icon and label, prefixed to avoid collisions.
RegistrationAn init callback calls register_element with the file, name and class.
The same class feeds the builder panel, the canvas and the front end; a failure low in the stack breaks everything above it.
Rendered output of the code above
Two columns of page text. In the left column, labelled for visitors, two paragraphs follow each other with nothing between them. In the right column, labelled as the builder, a small info callout titled Callout: add a title or text sits between the same two paragraphs.
A plain HTML and CSS render of what the callout prints when its title and text are empty: nothing for visitors, a hint callout where an editor can see it; not a screenshot of the Bricks editor.

Optional JavaScript and nestable elements

The callout works without JavaScript, which is the best kind of element. When an element does need behaviour, there are two pieces: the script file, loaded through enqueue_scripts() exactly like the stylesheet, and the $scripts property. The documentation describes $scripts as an array of JavaScript function names that run when the element is rendered on the front end or updated in the builder, with the Counter element’s bricksCounter function as its example, and it tells you to prefix your names.

Be careful with that property. A forum answer on custom elements says the listed functions are called inside the builder when the element renders or updates, and that for the front end you have to call your own function yourself. That is consistent with how a script file works, and it costs nothing to be safe: define one initialiser, list it in $scripts so the builder runs it after each update, and also call it on DOMContentLoaded for visitors. Make it safe to run more than once, since the builder will run it repeatedly. Test both environments instead of trusting either description.

As an example, let the callout be dismissible. Add a checkbox control, a data attribute in render(), the script property and the script enqueue.

// Property on the class.
public $scripts = [ 'wprCalloutInit' ];

// In set_controls().
$this->controls['dismissible'] = [
	'tab'    => 'content',
	'group'  => 'text',
	'label'  => esc_html__( 'Allow dismissing', 'wpr-bricks' ),
	'type'   => 'checkbox',
	'inline' => true,
	'small'  => true,
];

// In enqueue_scripts(), after the stylesheet.
wp_enqueue_script(
	'wpr-callout',
	WPR_BRICKS_URL . 'assets/callout.js',
	[],
	filemtime( WPR_BRICKS_DIR . 'assets/callout.js' ),
	true
);

// In render(), after the class attributes are set.
if ( ! empty( $settings['dismissible'] ) ) {
	$this->set_attribute( '_root', 'data-dismissible', 'true' );
}

The checkbox follows the documented pattern: a present value means checked, so ! empty() is the right test. The attribute lets the script find only the callouts that opted in. The script itself is plain JavaScript with no library.

function wprCalloutInit() {
  document.querySelectorAll('.wpr-callout[data-dismissible]').forEach(function (root) {
    var box = root.querySelector('.wpr-callout__box');
    if (!box || box.querySelector('.wpr-callout__close')) { return; }

    var button = document.createElement('button');
    button.type = 'button';
    button.className = 'wpr-callout__close';
    button.setAttribute('aria-label', 'Dismiss this note');
    button.textContent = '\u00d7';
    button.addEventListener('click', function () { root.hidden = true; });
    box.appendChild(button);
  });
}

document.addEventListener('DOMContentLoaded', wprCalloutInit);

The function finds every dismissible callout, skips any that already has a close button so repeated runs do not add duplicates, creates a real button with an accessible name, and hides the callout on click. The button needs a little CSS too, so add this to assets/callout.css.

.wpr-callout__box {
  position: relative;
}
.wpr-callout[data-dismissible] .wpr-callout__box {
  padding-right: 3rem;
}
.wpr-callout__close {
  position: absolute;
  top: 0.4rem;
  right: 0.5rem;
  width: 2rem;
  height: 2rem;
  padding: 0;
  border: 0;
  background: transparent;
  color: var(--wpr-callout-accent);
  font-size: 1.5rem;
  line-height: 1;
  cursor: pointer;
}
.wpr-callout__close:focus-visible {
  outline: 2px solid currentColor;
  outline-offset: 2px;
}

The box becomes the positioning context, so the button sits in its top right corner, and the extra right padding on dismissible callouts keeps a long title from running underneath it. The button gets a 2rem square target, no browser background or border, and the variant’s accent colour, so it matches every variant without extra rules. The :focus-visible rule draws a ring only for keyboard users, using the current text colour, which is what makes the control usable without a mouse. One more detail: the script hides the callout with the hidden attribute, and an author rule that sets a display value on .wpr-callout would override it, so if you ever add one, also add a rule that sets display: none for callouts that carry the hidden attribute. If you remember the dismissal across page views you would add storage and a way to reset it, which is a design decision beyond this example.

Nestable elements follow a different pattern. Setting $nestable = true tells Bricks the element can contain other elements; you define the default structure in a get_nestable_children() method that returns an array of element definitions, and your render() prints the children through the frontend class’s render_children method with the element instance as its argument, wrapped in your root tag. The documentation names three built-in nestable elements to study, the accordion, slider and tabs files in the Bricks theme. If you need nesting, read the nestable elements article in the developer documentation first; it covers the builder-side template as well, which is more involved than the flat element in this guide.

Rendered output of the code above
Two info callouts, each with a close button in the top right corner. The first shows the button at rest. The second shows the same button with a visible keyboard focus ring around it.
A plain HTML and CSS render of the dismissible callout with the close button CSS from this section, at rest and with keyboard focus; not a screenshot of the Bricks editor.

A testing checklist for a custom element

Custom elements fail in ways that built-in elements do not, because they are your code running inside someone else’s builder. Test on a staging copy with WP_DEBUG and WP_DEBUG_LOG enabled so notices and warnings land in the log instead of disappearing. Work through the list in this order; each step catches a different class of problem.

  1. Registration. Activate the plugin or child theme. Open the builder and search the elements panel for the label and for a keyword. The element should appear under the right category, with the right icon. Search the debug log for fatal errors if it does not.
  2. Defaults. Drop the element on a page without changing anything. It should render something sensible, with no PHP notice about a missing array key.
  3. Every control. Change each control and watch the canvas. Change the variant through all four values, change the heading tag, edit the text, and toggle optional checkboxes. Confirm the style tab controls change only the callout you selected.
  4. Empty and extreme values. Clear the title and the text. Visitors should see nothing, and the builder should show the hint. Then paste a very long title and a long body to see how the layout copes.
  5. Hostile input. Type markup into the title, such as an angle-bracket script tag, and a script tag with an event handler into the rich text. The front end must show the title as text and must strip the script from the body. View the page source rather than trusting how it looks. The figure at the end of this section shows the result to expect.
  6. Dynamic data. Insert a dynamic tag such as the post title in both text controls, on a template with a preview post and on a real page. Confirm the value resolves on the front end and in the canvas, and that a title containing special characters stays safe.
  7. Style tab and classes. Add a custom CSS class and a custom ID in the style tab and confirm both appear in the front-end markup. If they do not, the root attributes are not being printed.
  8. Assets. View the source of a page with the element and a page without it. The stylesheet and script should load only on the first. Check that the file version changes when you edit the file.
  9. Copy and paste. Copy the element and paste it on another page and another site on staging, then paste styles between two callouts. Variants and content should survive, and the controls marked not to paste styles should not be overwritten by a styles paste.
  10. Responsive and keyboard. Check the element at several breakpoints with the builder’s responsive switcher, and tab through it. Any interactive part, such as the dismiss button, needs a visible focus state and an accessible name.
  11. Environment changes. Deactivate the plugin and reload a page that uses the element. Reactivate it. Then update Bricks on staging, if an update is waiting, and run the whole list again before updating production.
  12. Debug log. After the full run, read the log. A clean run means no notices, warnings or deprecations from your files.

Two further checks suit teams. Run a PHP linter and the WordPress coding standards over the element files as part of review, since a stray bracket in an element file affects every page that uses it. And keep a short note in the plugin readme listing each element, its name and its control IDs, so a later maintainer knows what is safe to rename and what is not. Once the element is in use, treat the name and the control IDs as frozen, and add new controls instead of repurposing old ones.

Rendered output of the code above
On the left, the hostile text typed into the title and text controls: a script tag in the title and bold text plus a script tag in the rich text. On the right, a red Danger-style callout that prints the title as visible literal text and shows the body with bold text and the leftover word alert(1) as plain text, with no script tag.
A plain HTML and CSS render of the hostile-input test: the title is printed as literal text by esc_html, and wp_kses_post removes the script tags from the rich text; not a screenshot of the Bricks editor.

What goes wrong: symptoms, causes and fixes

When an element misbehaves, work from the bottom of the stack upward: is it registered, is the class valid, do the controls exist, does it render, do the assets load. Most problems are found by the third step.

  • The element is missing from the panel. The registration did not run, or the file failed to load. Check that the plugin or child theme is active, that Bricks is the active theme, that the file path in the registration is correct, and that no fatal error is in the debug log. Confirm the callback runs on init. If the element appears under an odd category label, the translatable string for a custom category is missing.
  • The element is in the panel but the canvas is blank or shows an error. The render method threw an error or returned nothing for the current settings. Check the log. If the element is meant to print nothing when empty, make sure the builder shows a hint.
  • The style tab does nothing. Either $css_selector points at a class that no element carries, or the root tag is not printing its attributes. Remove the property unless you need it, and print render_attributes( '_root' ).
  • A custom class or ID added in the builder is missing on the front end. The root attributes are not being printed. Fix the outermost tag.
  • A control change does not update the canvas. The key in $this->settings does not match the control ID, often a typo or a changed ID. Print the settings array temporarily to see what is stored, then remove the debug output.
  • Saved values vanished after a rename. The control ID or the element name changed, so pages hold values under the old key. Restore the old names or migrate the data on staging.
  • PHP notices about undefined array keys. The render method assumed a setting exists. Use isset, a fallback value or the null coalescing operator for every key.
  • The stylesheet loads on every page, or on none. If it loads everywhere, something enqueues it in a global hook. If it loads nowhere, the method name is probably misspelled, or a page cache is serving old markup. Rename carefully: it is enqueue_scripts on the element class.
  • The script works in the builder but not for visitors. The function was only called through $scripts. Call the initialiser on DOMContentLoaded as well.
  • A fatal error appears when switching themes. The element class is being loaded while the Bricks classes do not exist. Keep the class_exists guard and register only inside it.
  • The output differs on one site only. Site code may be using filters such as bricks/element/settings or bricks/frontend/render_element. Search that site’s code for them.

When a problem resists all of this, reduce the element to the smallest version that reproduces it: one control, a render that prints a fixed string inside the root tag, no assets. If that works, add pieces back one at a time. If it does not, the fault is in registration or the environment, not your logic. Also keep a copy of the Bricks developer pages for elements and controls in your notes; they are the reference the framework itself is built against, and they are updated more often than any article.

Checklist

  • Decided that a custom element is needed because a global class, component or template cannot express the controls or logic.
  • Gave the element a prefixed name, a custom class name with a vendor prefix and a single file, and treated the name as permanent once pages use it.
  • Set the category, icon and a localised label, and supplied the category label through the Bricks i18n filter if the category is custom.
  • Defined controls with closed choices where possible, using select controls for variants instead of free text fields.
  • Set pasteStyles to false on controls that output content rather than CSS.
  • Omitted the css selector property unless a child element really needs the default styles, and printed render_attributes for the root key on the outermost tag.
  • Gave render its own fallbacks for every setting instead of relying on control defaults.
  • Validated select values against the same list the control offers and allowed only known tag names.
  • Escaped every output: esc_html for text, wp_kses_post for rich text, esc_attr and esc_url for attributes and links.
  • Passed text through the dynamic data helper before escaping so tags resolve in the right post context.
  • Handled empty values with nothing for visitors and a visible hint in the builder.
  • Enqueued styles and scripts inside the element’s enqueue method so they load only on pages that use it, with a prefixed handle and a file-based version.
  • Registered the element on init after the theme has loaded, behind a guard that checks the Bricks classes exist.
  • Kept the code in a site plugin or the child theme under version control, and never edited the Bricks theme files.
  • Tested the element in the builder and on the front end with empty, long and hostile values, dynamic data, copy and paste, and debug logging on.
  • Re-ran the tests on staging after a Bricks update before updating the live site.

About this guide. This is general guidance written by WPresident Editorial from documentation and widely used practice. WPresident has not benchmarked the products or methods described. Interfaces and plan limits change, so check the vendor’s current documentation before you act. Not legal, tax or financial advice. See our editorial policy.

Frequently asked questions

Which class do I extend to create a Bricks element?

You extend the Bricks element class, written as the Element class in the Bricks namespace. Set the category, name, icon and the other properties, then implement the label, the controls and the render method. The label method, the controls method and the render method are the three the documentation marks as required. Prefix your own class name and the element name so they cannot collide with Bricks or other plugins, and keep each element in its own file.

Where do I register a custom element?

Register it on the WordPress init hook with a priority of 11, as the Bricks documentation shows, by calling the register_element method of the Bricks elements class with the file path and, ideally, the element name and class name. Put this in a small site plugin or in the child theme's functions file. Guard the call so nothing runs when the Bricks classes do not exist, for example when another theme is active.

Should the element live in a child theme or a plugin?

Both work. The Bricks documentation example uses the child theme. A plugin is usually better for elements that are part of how the site works, because you can switch it off to debug, reuse it on another site and keep it independent of the design. A child theme is simpler for small presentation elements tied to one design. Either way, keep the code in version control and never edit the Bricks parent theme files.

Why do my style tab controls do nothing in my custom element?

The usual causes are a css selector property pointing at a class that no element in your markup carries, or a root tag that does not print its attributes. Bricks applies the built-in style controls to the root element, so the outermost tag must output the root attributes from render_attributes. Remove the selector property unless you have a child element that should receive the default styles, and check the generated markup in the browser tools.

How do I make a script or stylesheet load only when my element is used?

Enqueue it inside the element's enqueue_scripts method instead of a global enqueue hook. The Bricks documentation says assets enqueued there load only on pages where the element appears. Use a prefixed handle, a URL from your plugin or theme, and a version based on the file's modified time so browsers refresh it after changes. Then view the source of a page without the element to confirm it is absent.

How do I escape output in a Bricks element?

Escape at the moment of output, using the function that matches the destination. Use esc_html for plain text, wp_kses_post for rich text from an editor control, esc_attr for attribute values, esc_url for links, and a whitelist check plus tag_escape for tag names. Resolve dynamic data first, then escape the resolved string. Do not copy documentation samples that echo settings directly, because they are shortened for clarity and are not production safe.

Can I use dynamic data inside a custom element?

Yes. The documentation describes helper methods on the element: one renders a string that may contain dynamic data tags, and one renders a single tag. They set the correct post context for the environment, whether the element is in the builder or on the front end. Call the helper on the setting value, then escape the result for where you print it. Test with a preview post on templates, and with special characters in the source field.

What does the scripts property do?

The documentation describes it as an array of JavaScript function names that run when the element is rendered on the front end or updated in the builder. A forum answer reports that, for custom elements, the functions are called in the builder and you must call your own initialiser for visitors. Define one idempotent initialiser, list it in the property, and also call it on DOMContentLoaded. Test both the builder and the front end.

Can a custom element contain other elements?

Yes, by setting the nestable property to true, defining the default children in a get_nestable_children method, and rendering them with the frontend class's render_children method inside your root tag. The developer documentation has a dedicated article on the nestable elements API and names the accordion, slider and tabs files as examples to study. It is a larger topic than a flat element, so build and test a flat element first.

Do I need to do anything when Bricks updates?

Test. Elements are your code, so a Bricks update can change something you depend on, such as markup, class names or builder behaviour. Update on a staging copy first, run the element through the testing checklist, read the debug log, and only then update production. Keep an eye on the changelog for notes on elements and controls, and keep your element files small so they are easy to review.

Is it safe to enable code execution instead of writing an element?

Executable code is a security-sensitive feature. Bricks documents that it runs only when code execution is enabled, the user has the execute-code capability and the code has a valid signature, and it advises granting access to as few trusted users as possible. For shared logic, a custom element in version control is easier to review and roll back than code stored in page data. Prefer the element for anything that many editors rely on.

W
Written byWPresident EditorialThe WPresident editorial team. Every article says whether it comes from hands-on use or from documentation, and anything paid for is labelled.

Keep reading

Get the Monthly Launch Report

One email a month: the best of last month's articles, new reviews and what changed in WordPress, without the noise.

No spam. Unsubscribe in one click.

Signed and sealed,
The WPresident
↑↓ move↵ openEsc closeAll results