Bricks Builder ships with a large set of dynamic data tags: post title, featured image, author name, taxonomy terms, custom fields, dates, URL parameters and more. They cover most of what a template needs, and then one day they do not. A client wants “6 min read” on every post card. A product page needs a number formatted with the site’s own separators. An About page should say how many years the company has been trading and stay correct next year without anyone editing it. None of these is a field in the database, so no tag exists for them, and the temptation is to paste PHP into a Code element or hard-code the text and hope nobody forgets to update it.
A custom dynamic data tag is the cleaner answer. It is a small piece of PHP, registered once, that gives you a named value you can drop into text, links, images and attributes in any template, using the same curly brace syntax as the built-in tags. Editors see it in the picker and use it without touching code. When the logic changes, you change it in one place instead of in forty templates.
The single most important idea in this tutorial is that a dynamic tag is just a string that Bricks replaces when it renders, and a custom tag takes part in that replacement through three documented hooks: one that lists the tag in the picker, one that resolves a single tag, and one that resolves tags embedded inside longer strings. Everything else here, from arguments and fallbacks to escaping and caching, is about doing those three jobs carefully. Once you see the pattern, adding a fourth or fifth tag is a few lines.
You will build three complete tags: a reading time tag, a formatted price tag and a years since tag. Along the way you will structure the code as a small registry so that new tags are one array entry, learn how arguments after a colon work, see what to return for text, link and image contexts, escape every value correctly, cache the expensive ones, and debug a tag that prints literally instead of resolving. There is also a security checklist for the output you produce, because a dynamic tag runs on every page that uses it and is a natural place for a slip to spread.
A few honest boundaries. This is a general guide based on the public Bricks documentation and WordPress core behaviour, not a test report, and it contains no benchmark numbers. Hook names and signatures in this tutorial were checked against the Bricks Academy. Where the documentation is silent, for example on exactly how key-value arguments reach your callback or in what order internal steps run, the text says so and shows how to find out on your own install. Bricks changes between versions, so check the current documentation for anything that matters to your site. And before you write any code, read the next two sections, because the right answer is sometimes not a custom tag at all.
Key points
- A custom tag needs three hooks: bricks/dynamic_tags_list to appear in the picker, bricks/dynamic_data/render_tag to resolve one tag, and bricks/dynamic_data/render_content plus bricks/frontend/render_data to resolve tags inside longer strings.
- Prefix every tag name so it cannot collide with a built-in tag or another plugin, and keep one registry array so adding a tag never means touching the hooks again.
- Use the post Bricks passes to your callback, not the global post, because inside a query loop the current item is the loop result.
- Return plain, escaped values for text, a URL for link contexts, and an array starting with an attachment ID for image contexts.
- Treat every argument as untrusted: allow-list meta keys, validate dates and numbers, and never build function names or queries from an argument.
- Cache anything that queries the database or calls an API, and remember a page cache freezes tags that depend on the current time or user.
- For a single custom field or one existing PHP function, a meta value filter or the echo tag can be simpler than a full custom tag.
What a dynamic data tag is and how Bricks resolves it
When you type an opening curly brace in a Bricks text setting, a picker opens and lists the available tags. Pick one and Bricks inserts text such as {post_title} into the setting. That is all a tag is while you edit: a string in curly braces stored inside the element’s settings. Nothing is computed in the builder panel. The computing happens later, when Bricks renders the element, finds the curly brace patterns in its settings and replaces each one with a value.
That replacement is a pipeline with documented entry points. The Bricks documentation describes a helper called bricks_render_dynamic_data that takes a string, an optional post ID and a context, and returns the string with tags replaced. The context says where the value will be used: text, link, image or media. Under that helper sit filters. One filter, bricks/dynamic_data/render_content, receives whole strings that may contain several tags, and Bricks attaches its own parser to it. Another, bricks/dynamic_data/render_tag, is applied to each individual tag found in the content, and it is where a custom tag is resolved. The documentation also lists a final filter that can adjust the processed value of any tag and an action that fires after a tag is parsed, which is useful for debugging.
Core tags are handled by providers. Bricks registers providers for WordPress itself, for WooCommerce and for the custom field plugins it integrates with, and a filter exists that lets you add or remove provider keys. The public documentation covers the simpler route for your own tags, which is to hook the filters directly. This tutorial follows that route because it is documented, stable and short.
The same strings can be used in many places. Dynamic data works in text settings, in non-text settings through a dropdown, in custom HTML attributes, in element conditions and in query settings such as meta query values. Everywhere a core tag works, a registered custom tag should work too, because the replacement happens in the shared pipeline. That reach is the reason to build tags carefully: one mistake in a tag can appear in every template that uses it.
Context matters more than it first seems. The same tag used in a text setting, a link setting and an image setting is asked for a string, a URL and an image respectively. A tag that always returns a decorated HTML string works in the first case and breaks the other two. The section on contexts later in this guide covers how to answer each one properly. For now, keep the picture in mind: a string with braces goes in, Bricks finds the tag, asks the providers and filters for its value in the right context, sanitises the result and puts it into the page.
How a custom tag is resolved at render time
- Setting holds a stringFor example Reading time: {acme_reading_time} inside a text setting
- Bricks runs the content parserbricks_render_dynamic_data or the element render path starts the replacement
- Content filters see the whole stringbricks/dynamic_data/render_content and bricks/frontend/render_data
- Each tag is resolvedbricks/dynamic_data/render_tag is applied per tag; your callback returns the value
- Value is formatted and sanitisedContext decides the shape; text context is sanitised by default
- Output replaces the tagAn action fires after parsing, which helps when debugging
Pick the right tool before you write a custom tag
A custom tag is the most flexible option and also the one with the most code to maintain. Bricks offers lighter tools for smaller jobs, and choosing the lightest one that works is usually right. Ask what you actually need.
You only want a different format for one existing custom field. The documentation lists a filter whose name ends with the meta key, so bricks/dynamic_data/meta_value/my_price_field runs whenever {cf_my_price_field} is output, receiving the value and the post. Return a formatted string and every template that already uses the tag is fixed at once. It formats one key. It does not add a tag to the picker and it does not take arguments.
You need a date shown in a different format. Bricks has a built-in date formatting tag that takes a date string, the input format and the output format. Check the Bricks Academy page on dynamic data before writing PHP for date display.
You want to call one existing PHP function from a template. The echo tag does this: {echo:my_function('argument')}. The documentation attaches strict conditions. Code execution has to be enabled for the user in the Bricks settings, every callable function name has to be allowed through the bricks/code/echo_function_names filter, arguments must use single quotes, and the function must return its value rather than print it. It suits a private site with trusted editors and a handful of helpers. It is a poor fit for a team, because each function is a permission decision and the template carries PHP-shaped syntax.
You want to change every tag’s output the same way. The bricks/dynamic_data/format_value filter receives the final value of any tag along with the tag name, the post ID, the filters applied and the context. It is powerful and risky for the same reason: it runs for everything.
You want a named, reusable value with arguments that editors can pick and reuse. That is a custom tag. Use it when the value is computed rather than stored, when several templates need it, when it takes an argument, or when you want it listed in the picker under your own group.
A fair question is whether a ready-made element already does the job. Bricks includes a post reading time element with settings for the source content, a prefix, a suffix, words per minute and a words or characters calculation method. For a plain “Reading time: 6 min” line, use it. A custom reading time tag earns its place where an element cannot go: inside a heading, a card’s meta line built from several tags, an element condition or an attribute. The reading time tag in this guide is a teaching example for exactly that reason, and it is simple enough to show every part of the pattern.
Which tool fits the job
Where the code goes and how to name things
Custom tag code is ordinary PHP that hooks into Bricks, and you have three sensible places for it. Never put it in the Bricks parent theme. The Bricks documentation is blunt about this: updates replace the theme, and your changes disappear with them.
- A small site plugin is the best home for tags that describe your data or business rules. It survives theme changes, can be activated per site, and can be deployed like any other plugin. The examples in this tutorial are written as one plugin file.
- The Bricks child theme is fine when the tags are inseparable from the design. Its
functions.phpis loaded in addition to the parent theme’s, as the Bricks documentation explains. The downside is the same as for any theme code: switch themes and the tags vanish, and every template that used them prints raw curly braces. - A code snippets plugin works for experiments. For anything a client relies on, move it to a plugin file under version control.
Code execution is not needed for any of this. Custom tags are plain PHP files on the server, loaded by WordPress like any plugin. The Bricks setting for code execution governs code typed into the builder, such as the Code element, the Query editor and the echo tag, which is part of why a registered tag is a cleaner approach for team sites: no builder user needs a permission to run code for the tag to work.
Naming deserves a few minutes of thought because the name is a permanent interface. The Bricks documentation advises making your tag unique and says it is best to prefix it. Choose a short prefix that identifies your project and use it for the tag name, the PHP function names and any options. This tutorial uses acme_ as a stand-in, so replace it with your own. Prefixing prevents three kinds of trouble. It stops a collision with a core tag or a future Bricks tag with the same name. It stops a clash with another plugin that registers a tag called something generic like price. And it makes the picker group and your own code easy to search.
Keep tag names lowercase with underscores, because the examples in the documentation do and the parsing code in this guide assumes it. Keep arguments after a colon, as in {acme_price:ticket_price}, because that is the form the documentation’s argument example uses. Decide early whether a name describes the data (acme_reading_time) or the presentation (acme_bold_price). Data-shaped names age better, because presentation belongs to the template.
One last structural choice. Keep tag code out of the main plugin file once it grows. A folder with one file per tag and a registry file that lists them keeps each tag short and testable. For three tags, a single file is fine, and that is what the next sections build.
Step 1: list the tag in the picker with bricks/dynamic_tags_list
The first hook only decides what editors see. The Bricks documentation describes bricks/dynamic_tags_list as the filter for the list of tags in the builder’s dynamic data picker. You receive an array of tag definitions and return it with yours added. Each definition has a name, which is the tag including its curly braces, a label shown in the picker, and a group that the picker uses to organise tags. The code below is the top of the plugin file: a registry function that describes every tag in one place, and the hook that publishes the registry to the picker.
<?php
/**
* Plugin Name: Acme Bricks Tags
* Description: Custom dynamic data tags for Bricks Builder.
* Version: 1.0.0
* Text Domain: acme-bricks-tags
*/
defined( 'ABSPATH' ) || exit;
/**
* One entry per tag. Add a tag here and the hooks below pick it up.
* The key is the tag name without braces; the callback receives ( $argument, $post, $context ).
*/
function acme_tags() {
return [
'acme_reading_time' => [
'label' => __( 'Reading time', 'acme-bricks-tags' ),
'callback' => 'acme_tag_reading_time',
],
'acme_price' => [
'label' => __( 'Formatted price (argument: meta key)', 'acme-bricks-tags' ),
'callback' => 'acme_tag_price',
],
'acme_years_since' => [
'label' => __( 'Years since (argument: year, date or field)', 'acme-bricks-tags' ),
'callback' => 'acme_tag_years_since',
],
];
}
add_filter( 'bricks/dynamic_tags_list', function ( $tags ) {
foreach ( acme_tags() as $name => $tag ) {
$tags[] = [
'name' => '{' . $name . '}',
'label' => $tag['label'],
'group' => 'Acme',
];
}
return $tags;
} );
What each part does. acme_tags() is the registry. It returns a plain array keyed by tag name, with a human label and the name of the function that produces the value. Keeping the list in a function means the picker hook, the single tag hook and the string hook all read the same source, so they cannot drift apart. The hook adds one definition per entry, wrapping the name in curly braces. The labels run through __() so they can be translated, and the picker group is a plain string that Bricks displays as a heading for your tags.
Activate the plugin, open any template in the builder and type an opening curly brace. Your group should appear with the three tags. If it does not, reload the builder, because it loads the tag list when it opens. Then notice what the picker does not tell you: it only lists. Insert {acme_reading_time} and view the page, and you will see either literal braces or nothing, depending on how Bricks handles tags it cannot resolve. The Bricks documentation lists a filter named bricks/dynamic_data/replace_nonexistent_tags that disables its default behaviour of replacing unknown tags with an empty string, which is a clue about what the default is. Either way, a registered but unresolved tag shows nothing useful, and the next two sections fix that.
A word on arguments in the picker. The picker inserts the tag name only. Editors who need an argument type it after the colon, for example {acme_price:ticket_price}. That is why the labels above mention the expected argument: it is the only hint editors get at the point of choosing. Write short, accurate labels.
Step 2: resolve one tag with bricks/dynamic_data/render_tag
The second hook turns a tag into a value. The documentation describes bricks/dynamic_data/render_tag as the filter that resolves a single dynamic data tag, applied for each individual tag found in the content. Your callback receives three things: the tag as a string without curly braces, which can include arguments such as post_title:fallback, the post context, and a context string that says where the value will be used. The documented rule for a callback is simple. If the tag is yours, return its value. If it is not, return the original tag unchanged so that other providers and filters can handle it.
Two helpers keep the callback tiny. One splits a raw tag into a name and an argument. The other looks the name up in the registry and calls the right function. Add both to the plugin file, followed by the filter.
/**
* Split "acme_price:ticket_price" into [ 'acme_price', 'ticket_price' ].
*/
function acme_split_tag( $raw ) {
$raw = trim( str_replace( [ '{', '}' ], '', (string) $raw ) );
$parts = explode( ':', $raw, 2 );
return [ $parts[0], isset( $parts[1] ) ? $parts[1] : '' ];
}
/**
* Resolve one raw tag. Returns null when the tag is not ours.
*/
function acme_resolve( $raw, $post, $context ) {
list( $name, $argument ) = acme_split_tag( $raw );
$tags = acme_tags();
if ( ! isset( $tags[ $name ] ) ) {
return null;
}
$post = get_post( $post );
if ( ! $post instanceof WP_Post ) {
return '';
}
return call_user_func( $tags[ $name ]['callback'], trim( $argument ), $post, $context );
}
add_filter( 'bricks/dynamic_data/render_tag', function ( $tag, $post, $context = 'text' ) {
if ( ! is_string( $tag ) ) {
return $tag;
}
$value = acme_resolve( $tag, $post, $context );
return null === $value ? $tag : $value;
}, 20, 3 );
Walk through it. acme_split_tag strips curly braces defensively, which is what the Bricks example does, so the code works whether Bricks hands you braces or not. It splits on the first colon only, so an argument that itself contains a colon, such as a time, stays intact. acme_resolve returns null for any tag that is not in the registry, and that null is the signal for the filter to hand the original tag back. For a tag that is ours, get_post normalises whatever the caller passed, whether a post object, an ID or null, into a post object, and the callback gets the post, never the global.
That last point is easy to miss and expensive when missed. Inside a Bricks query loop the current item is the loop result, and the Bricks documentation says dynamic data resolves against the current loop result. If your callback calls get_the_ID() or reads the global post, it will describe the page, not the card. Always use the post that Bricks passes in. The callback runs at priority 20 with three accepted arguments, which follows the documented example and gives Bricks and other code a chance to run first. The context defaults to text so the filter still works if a caller omits it.
Notice what the callback returns. It returns whatever the tag function returns, which is normally a string but may be an array in an image context, and Bricks decides what to do with it. That is why the filter does not cast to string. The string hook in the next section does, because it is pasting values into text.
The render below shows what the global post mistake looks like. It uses a page whose own content takes nine minutes to read and a loop of three cards, with example numbers. When the callback reads the global post, every card repeats the page’s number. When it uses the post that Bricks passes in, each card reports its own.

Step 3: resolve tags inside longer strings
Single tag resolution is not the whole story. Most of the time Bricks is not asked to resolve a lone tag. It is given a string such as Reading time: {acme_reading_time} | By {author_name} and asked to resolve everything in it. The Bricks documentation covers this with two filters that handle whole strings, bricks/dynamic_data/render_content and bricks/frontend/render_data, and it attaches a warning worth repeating: take extra care here, because a mistake can disrupt dynamic tags across the entire website. The rules for staying safe are to return the content untouched whenever you have nothing to do, and never to return anything but a string.
function acme_render_content( $content, $post = null, $context = 'text' ) {
// Cheap exit: the vast majority of strings contain none of our tags.
if ( ! is_string( $content ) || false === strpos( $content, '{acme_' ) ) {
return $content;
}
$result = preg_replace_callback(
'/\{(acme_[a-z0-9_]+(?::[^{}]*)?)\}/i',
function ( $match ) use ( $post, $context ) {
$value = acme_resolve( $match[1], $post, $context );
if ( null === $value ) {
return $match[0];
}
// A string replacement cannot hold an array, so image style values are dropped here.
return is_array( $value ) ? '' : (string) $value;
},
$content
);
// preg_replace_callback returns null on an engine error; never hand null back to Bricks.
return null === $result ? $content : $result;
}
add_filter( 'bricks/dynamic_data/render_content', 'acme_render_content', 20, 3 );
add_filter( 'bricks/frontend/render_data', 'acme_render_content', 20, 2 );
How it works. The early return protects every other tag on the site: if the string has no {acme_ in it, the function hands it back without a single regular expression running. The pattern matches a tag that starts with your prefix, optionally followed by a colon and an argument made of anything except braces, and captures the part inside the braces, which is exactly what acme_resolve expects. Because the callback receives the full match, a tag it cannot resolve is returned as it was. The last two lines guard against a regular expression engine error, which makes preg_replace_callback return null, since handing null back to Bricks would blank the whole setting. The same function is registered twice, once for each filter, with three and two accepted arguments, which follows the documentation’s own example for argument-taking tags.
Why two filters? The documentation says the content filter is used when the dynamic data provider layer parses strings, and names bricks_render_dynamic_data as one function that triggers it. It lists the front end render data filter beside it without a separate explanation, so treat the exact split as an implementation detail. What matters is that the documented example registers both, and doing the same covers every path it covers. If you ever find a tag that resolves in one place but not another, check that both hooks are registered and that your priority is not being overtaken by something else.
The architecture is now complete, and it is worth seeing as layers. At the bottom are the callbacks, one function per tag, each returning a plain value. Above them is the registry that names the tags. Then come the three hooks, which are thin: they only translate between Bricks and the registry. Adding a tag from now on means writing one callback and one registry entry, with no new hooks.
Anatomy of a custom tag plugin
Worked example 1: a reading time tag
The first tag estimates reading time from a post’s content. The behaviour to build is small and precise. {acme_reading_time} returns a phrase such as “6 min read”. An optional argument sets the reading speed in words per minute, so {acme_reading_time:250} uses 250. The tag returns an empty string for a password-protected post, so it never hints at the length of content the visitor cannot see. The result is never less than one minute.
function acme_tag_reading_time( $argument, $post, $context ) {
// Do not reveal anything about content the visitor is not allowed to read.
if ( post_password_required( $post ) ) {
return '';
}
$wpm = ctype_digit( $argument ) ? (int) $argument : 200;
$wpm = max( 100, min( 600, $wpm ) );
$cache_key = 'rt_' . $post->ID . '_' . $post->post_modified_gmt . '_' . $wpm;
$minutes = wp_cache_get( $cache_key, 'acme_bricks_tags' );
if ( false === $minutes ) {
$text = wp_strip_all_tags( strip_shortcodes( $post->post_content ) );
$words = (int) preg_match_all( '/\S+/u', $text );
$minutes = max( 1, (int) ceil( $words / $wpm ) );
wp_cache_set( $cache_key, $minutes, 'acme_bricks_tags', HOUR_IN_SECONDS );
}
/* translators: %d: number of minutes */
return sprintf( esc_html__( '%d min read', 'acme-bricks-tags' ), $minutes );
}
Reading the callback from the top. The password check uses the post that Bricks passed in. The reading speed comes from the argument, but only if it is made of digits, and then it is clamped between 100 and 600, so a typo such as {acme_reading_time:0} cannot cause a division by zero or a silly result. The cache key includes the post ID, the modified time and the speed, so editing the post produces a new key and stale numbers never serve. The word count strips shortcodes and HTML tags and then counts whitespace-separated tokens, a deliberate simplification that works for space-separated languages. For languages written without spaces between words, count characters instead, which is why the built-in Bricks reading time element offers a characters method.
The final line formats the number through a translatable string and escapes it. The value is a plain string, so it works in any text setting. A line in a card might read {post_date} · {acme_reading_time}, which uses a core tag and your tag side by side. Because the callback returns text without markup, the template keeps full control of styling.
Two caveats. First, the tag reads post_content, which the Bricks documentation describes as the content from the WordPress editor. If a page’s text is composed from Bricks elements instead, the editor field may not hold it, so check how your content is stored before trusting the number, or use the built-in reading time element for those pages. Second, wp_cache_set only lasts for one request unless the site runs a persistent object cache. That is fine here, because the counting work is small. It matters for the expensive tags covered in the caching section.

Worked example 2: a formatted price tag
The second tag formats a number stored in a custom field. A price field holds a plain number such as 1234.5. A visitor should see it with the site language’s thousands and decimal separators, and perhaps a currency label. The tag takes the name of the meta key as its argument, so {acme_price:ticket_price} formats the ticket_price field of the current post. This example formats numbers rather than doing any currency conversion, and it uses no money values of its own: the number comes from your field.
/**
* Meta keys the price tag may read. Extend this list with the filter instead of editing the tag.
*/
function acme_price_meta_keys() {
return (array) apply_filters( 'acme_price_meta_keys', [ 'ticket_price', 'event_min_price' ] );
}
function acme_tag_price( $argument, $post, $context ) {
$key = sanitize_key( $argument );
// Allow-list: never read an arbitrary meta key chosen by whoever wrote the template.
if ( '' === $key || ! in_array( $key, acme_price_meta_keys(), true ) ) {
return '';
}
if ( post_password_required( $post ) ) {
return '';
}
$raw = get_post_meta( $post->ID, $key, true );
if ( ! is_numeric( $raw ) ) {
return '';
}
$decimals = (int) apply_filters( 'acme_price_decimals', 2, $key, $post );
$decimals = max( 0, min( 4, $decimals ) );
$label = (string) apply_filters( 'acme_price_currency_label', '', $key, $post );
return esc_html( trim( number_format_i18n( (float) $raw, $decimals ) . ' ' . $label ) );
}
What the code does. The argument is passed through sanitize_key and then checked against an allow-list. That list is the security core of this tag. Without it, a template author could write {acme_price:_edit_lock} or the name of any private meta key and have its contents printed on a public page. The tag returns an empty string for anything it does not recognise, a non-numeric value or a protected post. number_format_i18n is the WordPress function that applies the active locale’s separators, so the same stored number prints as 1,234.50 on an English site and 1.234,50 on a German one. Decimals and an optional currency label come from filters, so a site can change them without editing the plugin. The result is escaped with esc_html because it goes into a text node.
Returning an empty string for missing data is a deliberate design choice. It lets the template decide what an empty price means. An element condition set to is empty can show a “Price on request” message, and is not empty can show the price block. The Bricks documentation describes both comparisons for dynamic data conditions, and they check whether the rendered output of the tag is an empty string.
If your goal is only to format one existing field that templates already use through the custom field tag, you do not need a new tag. The documented meta value filter is lighter. It runs when that key is output through dynamic data and receives the value and the post.
add_filter( 'bricks/dynamic_data/meta_value/ticket_price', function ( $value, $post ) {
return is_numeric( $value ) ? number_format_i18n( (float) $value, 2 ) : $value;
}, 10, 2 );
This version changes the output of {cf_ticket_price} everywhere, with no picker entry and no argument. Choose it when one field needs one format. Choose the custom tag when editors need to format several fields, choose the decimals or reuse the formatter in places that do not use the custom field tag.

Worked example 3: a years since tag
The third tag shows a number that changes with time. {acme_years_since:2012} returns the number of full years between January 1 of 2012 and now, in the site’s timezone. The argument can be a four digit year, a full date in Y-m-d format, or the name of a date field on the current post, which makes the tag useful inside a team member loop that shows years of service or a product loop that shows the age of an item.
function acme_date_meta_keys() {
return (array) apply_filters( 'acme_date_meta_keys', [ 'event_date', 'founded_on', 'start_date' ] );
}
function acme_tag_years_since( $argument, $post, $context ) {
$source = $argument;
// Not a year or a date: treat the argument as the name of a date field on this post.
if ( ! preg_match( '/^\d{4}(-\d{2}-\d{2})?$/', $source ) ) {
$key = sanitize_key( $argument );
if ( '' === $key || ! in_array( $key, acme_date_meta_keys(), true ) ) {
return '';
}
$source = (string) get_post_meta( $post->ID, $key, true );
}
// A bare year means the first day of that year.
if ( preg_match( '/^\d{4}$/', $source ) ) {
$source .= '-01-01';
}
$zone = wp_timezone();
$start = DateTimeImmutable::createFromFormat( '!Y-m-d', $source, $zone );
// Reject anything that is not a real calendar date, such as 2025-02-31.
if ( ! $start || $start->format( 'Y-m-d' ) !== $source ) {
return '';
}
$now = new DateTimeImmutable( 'now', $zone );
if ( $start > $now ) {
return '0';
}
return (string) $start->diff( $now )->y;
}
Why it is written this way. Dates are where hand-rolled code goes wrong, so the callback leans on DateTimeImmutable instead of arithmetic with 365 days. The format string begins with an exclamation mark, which resets the time fields to midnight so two dates compare cleanly. After parsing, the code formats the result back and compares it with the input. This catches dates that PHP would otherwise quietly roll over, since a value like 2025-02-31 can parse into early March, and the tag returns an empty string instead of a wrong year. wp_timezone returns the timezone from the site’s general settings, so “now” means the site’s now, not the server’s. A start date in the future returns zero rather than a negative number.
The tag returns only the number. The word “years” stays in the template. That keeps translation and pluralisation where they belong, and it lets the same tag feed a sentence, a counter element or a condition. Date field arguments are checked against an allow-list for the same reason as in the price tag.
Think about when the answer goes stale. A years-since value changes at most once a year, so a page cache holding last month’s HTML is harmless. A tag that showed minutes or the current user’s name would not be, because a full page cache serves one stored copy to everyone until it expires or is purged. Decide for each tag whether its value is safe inside cached HTML, and if it is not, plan to exclude the page from caching or load that fragment separately.
The render below lists what the tag returns for several arguments, assuming an example site date of 17 November 2026 and a post whose founded_on field holds 2019-03-10. Notice the two empty results: an impossible date and a field name that is not on the allow-list both produce an empty string, so a template can react to them with an element condition.

Arguments, fallbacks and key-value syntax
Arguments make one tag do the work of many. The documented pattern is a colon followed by the argument, as in {my_dd_tag:arg1}, and the Bricks guide shows both the single tag filter and the string filter handling it. The code in this tutorial already follows that pattern. The helper splits on the first colon, and each callback decides what its argument means: a speed for reading time, a meta key for the price, a year, date or field name for years since.
When a tag needs more than one argument, split the argument again inside the callback. Here is the start of a price callback that accepts an optional second value for the number of decimals, so {acme_price:ticket_price:0} prints a whole number. The rest of the function stays as it was.
// At the top of acme_tag_price(): accept "key" or "key:decimals".
list( $key_part, $decimals_part ) = array_pad( explode( ':', $argument, 2 ), 2, '' );
$key = sanitize_key( $key_part );
// Later, where the decimals are chosen:
$decimals = ctype_digit( $decimals_part )
? min( 4, (int) $decimals_part )
: (int) apply_filters( 'acme_price_decimals', 2, $key, $post );
The lines show the habit to keep: every part of an argument is validated on its own. A key is cleaned and then allow-listed, and a number must be digits and is capped. Nothing from an argument ever reaches a function name, a query or a file path.
Bricks also documents a second argument style, key-value pairs written after the tag name, as in {acf_text_field @fallback:'No content was found'}. The documentation says @fallback works with any dynamic data tag, that @fallback-image does the same for images, and that @sanitize controls the sanitisation applied to text output. Values containing spaces go in single quotes, and a value can itself contain other tags. Whether and how these arguments reach a custom callback is not described in the guide for creating tags, whose examples use the colon form only. Do not assume. The documentation also lists a filter, bricks/dynamic_data/allowed_keys, that controls which argument keys are accepted, and its default list includes fallback, fallback-image, sanitize, exclude, start-at, pad, key, is-array, date, from and to. If you want a custom key, add it there, then observe what your callback receives.
The observation tool is an action that Bricks fires after it parses a tag. It receives the parsed value, the tag name, the original tag, the parsed arguments, the post, the context and the provider key, and the documentation stresses that it observes and does not change the returned value. A temporary logger answers the question for your own version in a minute.
add_action( 'bricks/dynamic_data/tag_value_parsed', function ( $value, $tag, $original_tag, $args, $post, $context, $provider ) {
if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG || 0 !== strpos( (string) $tag, 'acme_' ) ) {
return;
}
error_log( 'acme tag=' . $tag . ' original=' . $original_tag . ' args=' . wp_json_encode( $args ) . ' context=' . $context );
}, 10, 7 );
With debugging switched on, load a page that uses your tags and read the log. It shows the tag name Bricks parsed, the original string and the arguments it extracted. If key-value arguments appear in the argument array, you can read them in a callback or a filter. If they do not, stay with the colon form. Remove the logger when you are done, because it writes on every tag. For empty data, the dependable approach is the one used throughout this tutorial: return an empty string and let an element condition, is empty, show the alternative content.
Contexts: what to return for text, link and image
Bricks tells your callback where its value will be used. The helper function documentation lists four contexts: text, link, image and media. The filter for the final value mentions a few more, including video and object. Each context wants a different shape, and returning the wrong one is the usual reason a tag works in a heading but fails in a button or an image element.
Text is the easy case. Return a plain string that is safe to place inside an HTML text node. Link settings need a URL, not a sentence and not an anchor tag, since Bricks builds the anchor itself. Image settings are different again. The Bricks guide for creating tags adds a note on this: if your tag is used in an image context, return an array whose first item is an attachment ID or an image URL, and use an attachment ID when Bricks needs image size and srcset data. The next callback handles all three contexts for a tag that returns the site logo. Add it to the registry like the others, with the key acme_site_logo.
function acme_tag_site_logo( $argument, $post, $context ) {
$id = (int) get_theme_mod( 'custom_logo' );
if ( ! $id ) {
return '';
}
if ( 'image' === $context ) {
// First item is an attachment ID, so Bricks can build sizes and srcset.
return [ $id ];
}
// Link and text contexts get a URL string.
return esc_url( (string) wp_get_attachment_image_url( $id, 'medium' ) );
}
In an Image element, the tag is chosen through the dynamic data dropdown and Bricks receives the array with the attachment ID. In a link setting it receives the URL. The early exit returns an empty string when there is no logo, which every context treats as nothing to show. In a text setting the same tag prints the URL, which is harmless but rarely what an editor wants. If a tag only makes sense for one context, return an empty string for the others. The string filter from earlier also turns any array into an empty string, so an image style value can never leak into running text.
For media contexts that you cannot find documented, the safest method is to copy a core tag. Use the logging action from the previous section on a core tag of the kind you need, such as a video or file field, and mirror the shape of its value.
The same tags are available from your own PHP. The documented helper takes a string, an optional post ID and a context, and returns the string with tags replaced, so a shortcode or a template part can reuse the logic.
// In a shortcode callback or a template part.
echo wp_kses_post( bricks_render_dynamic_data( 'Reading time: {acme_reading_time}', get_the_ID(), 'text' ) );
Wrapping the result in wp_kses_post is a sensible habit when you print tag output yourself, because outside Bricks’ own render path you are responsible for the escaping. One more place deserves a mention: loops over terms or users. A tag written for posts receives a post object, but in a loop whose items are terms or users the current item is not a post, so check what your callback receives there and return an empty string when the tag does not apply.
What each context expects from a tag
| Where it is used | What to return | |
|---|---|---|
| text | Headings, text, attribute values | A plain string, escaped for an HTML text node |
| link | Link and URL settings | A URL string cleaned with esc_url |
| image | Image source settings | An array whose first item is an attachment ID, or a URL |
| media | Other media settings | Mirror the shape a core tag of that kind returns |
| nothing to show | Any context | An empty string, so conditions and fallbacks can react |
Escaping and validation: a security checklist for tag output
A dynamic tag sits between stored data and the page, which makes it a good place for mistakes and a good place to prevent them. Start by asking where the data comes from, because the answer decides how suspicious to be. Arguments are typed by whoever builds the template, and the Bricks documentation notes that tag values can contain other tags, so an argument can ultimately come from a URL parameter or a custom field. Meta values come from editors, contributors, importers and plugins. Post fields come from authors. None of it should be trusted to be harmless text.
Bricks sanitises tag output in the text context by default. The documentation says all dynamic tags in a text context are passed through wp_kses_post, which strips scripts and unwanted HTML, and it offers an @sanitize argument that can change or disable that. This is a safety net, not a licence to skip your own escaping. Your callback may be called from places that behave differently, a later version may change defaults, and escaping at the point where you build the value keeps the function safe in isolation.
Apply this checklist to every tag you write.
- Escape for the context. Plain text goes through
esc_html. A URL goes throughesc_url. A value that will sit inside an attribute goes throughesc_attr. Markup you intend to allow goes throughwp_kses_post, never raw. - Allow-list, do not block-list. Meta keys, field names and option keys named in an argument must be checked against a fixed list. Block-lists miss the key you did not think of.
- Validate types. Numbers pass
is_numericorctype_digitand are clamped to a sensible range. Dates are parsed and then compared with their formatted result. - Never turn an argument into code. No function names from arguments, no dynamic
include, no query fragments, no file paths. The echo tag exists for calling functions, behind code execution and an allow-list, and the documentation flags a related filter that allows recursive echo parsing as risky. - Respect post visibility. If a tag reveals anything derived from another post’s content, check
post_password_required, the post status and, where relevant,current_user_can( 'read_post', $post->ID ). - Do not read superglobals directly. If you need a URL value, take it through a documented tag argument or sanitise it yourself with
sanitize_text_field( wp_unslash( ... ) ). - Fail closed and quietly. Return an empty string on any problem. No notices, no stack traces and no file paths in the output, which could leak information about the server.
- Keep side effects out. A tag should read and compute. It should not write options, send email or call an API without a timeout and cache.
The render below shows why escaping matters even for text that looks harmless. The same stored value, written by a contributor, is shown without escaping on the left and with esc_html on the right. On the left the browser reads the markup and applies it. On the right the characters are shown as typed. With a bold tag the difference is cosmetic. With a script tag it would be a security hole.

Caching, testing and troubleshooting
Performance problems with tags have a typical shape. A tag is cheap on its own and expensive in a loop, because the loop calls it once per card. A tag that runs a database query or an HTTP request, placed in a twelve card grid, runs twelve times for every uncached page view. The cure is to cache anything that touches the database beyond the post it is given or reaches out to another server. WordPress offers the object cache for values that can live for the request or, with a persistent object cache, for longer, and transients for values with a lifetime. The helper below wraps the transient pattern so a callback can ask for a value and name a lifetime.
function acme_cached( $key, $ttl, callable $producer ) {
$cache_key = 'acme_dd_' . md5( $key );
$value = get_transient( $cache_key );
if ( false === $value ) {
$value = $producer();
set_transient( $cache_key, $value, $ttl );
}
return $value;
}
/**
* Example tag: {acme_published_count:event} prints how many public items of a post type exist.
*/
function acme_tag_published_count( $argument, $post, $context ) {
$type = sanitize_key( $argument );
$object = get_post_type_object( $type );
// Only public post types: counts of private types should not be readable from a template.
if ( ! $object || ! $object->public ) {
return '';
}
$count = acme_cached( 'count_' . $type, 15 * MINUTE_IN_SECONDS, function () use ( $type ) {
$counts = wp_count_posts( $type );
return isset( $counts->publish ) ? (int) $counts->publish : 0;
} );
return esc_html( number_format_i18n( $count ) );
}
The key is hashed so it stays short and safe whatever the argument was, and the lifetime is chosen by the caller. The example tag also shows the allow-list idea in a different form: it asks WordPress whether the post type is public instead of keeping its own list. Remember what caching cannot fix. A page cache stores final HTML, so a tag that depends on the time of day or on the logged-in user is only as fresh as the cached page. Keep such tags out of cached pages or load them separately.
Testing a tag is mostly about trying the awkward cases. Use a local or staging copy, with debugging switched on. If you use WP-CLI there, you can resolve a tag without opening a browser, using the documented helper function with a post ID.
$ wp eval 'echo bricks_render_dynamic_data( "Reading time: {acme_reading_time}", 123 );'
Replace 123 with a real post ID. Beyond that one-liner, a short test matrix catches most real faults: a post with no content, a password-protected post, a tag with no argument, a tag with a bad argument, an empty custom field, a tag inside a query loop on a page that is not the loop’s post, the same tag in the builder canvas and on the front end, and a site language that is not English.
When something is wrong, match the symptom to a likely cause.
- The tag is missing from the picker. The plugin is inactive or hit a fatal error, the list filter is not registered, or the builder was open before you added the tag. Reload the builder and check the PHP error log.
- The picker shows the tag but the page prints curly braces. The resolving hooks are missing or the name differs, often by case or a typo. Check that the registry key, the regular expression and the tag you typed agree exactly.
- The tag prints nothing. The callback returned an empty string on purpose: an argument is not on the allow-list, a meta value is missing or non-numeric, or the post is protected. Call the callback directly with a known post to see which branch fires.
- It works in text but not in an image or link setting. The return shape does not match the context. Return an array with an attachment ID for images and a URL for links.
- It shows the page’s data inside a loop. The callback used the global post or the current page’s ID instead of the post it was given.
- Other tags broke after you added the string filter. The filter returned something that was not a string, or altered content it should have left alone. Keep the early return and the null guard exactly as shown.
- A fatal error mentions an undefined function. A registry entry names a callback that does not exist. Check spelling and that the file defining it is loaded.
- The value is stale. A transient or a page cache is holding it. Purge, shorten the lifetime or exclude the page.
- A tag stopped working after a Bricks update. Compare the hooks you use with the current documentation, then run the test matrix on staging before updating production.
One last habit. The hooks in this guide are all listed in the Bricks documentation, but they are still part of a product that changes. Keep your tag code small, keep the three hooks thin, and keep a staging site where Bricks updates are tried first. A short plugin with a clear registry is easy to adapt when an extension point changes.
Checklist
- Decide first whether a meta value filter, the date format tag, the echo tag or an existing element would do the job instead of a custom tag.
- Put the code in a small site plugin or the child theme, never in the Bricks parent theme.
- Choose a unique prefix for tag names, function names and options, and use it everywhere.
- Keep one registry array listing every tag with its label and callback.
- List tags in the picker with the bricks/dynamic_tags_list filter, and reload the builder to confirm they appear.
- Resolve single tags with bricks/dynamic_data/render_tag and return the original tag untouched when it is not yours.
- Resolve tags inside longer strings with both bricks/dynamic_data/render_content and bricks/frontend/render_data, with an early exit and a string-only return.
- Use the post Bricks passes to the callback, never the global post, so tags work correctly inside query loops.
- Allow-list every meta key, field name or option key that an argument can name.
- Validate numbers and dates, clamp ranges, and compare parsed dates with their formatted result.
- Escape output with esc_html, esc_attr, esc_url or wp_kses_post to match where the value will be used.
- Return an array with an attachment ID first for image contexts and a URL string for link contexts.
- Return an empty string when there is nothing to show, so element conditions can display alternatives.
- Check password protection and post visibility before revealing anything derived from a post’s content.
- Cache queries, HTTP calls and heavy calculations with the object cache or transients, and decide whether page caching is safe for each tag.
- Log parsed arguments with the tag_value_parsed action while developing, then remove the logger.
- Run a test matrix: empty content, protected post, missing and bad arguments, loop context, builder canvas and front end.
- Retest all custom tags on a staging copy after each Bricks update.
Read this next
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
Do I need to enable code execution in Bricks to use a custom dynamic data tag?
No. A custom tag is ordinary PHP in a plugin or child theme that hooks into Bricks filters, so no builder user needs the execute code permission for it to work. The Bricks code execution setting applies to code typed into the builder, such as the Code element, the Query editor and the echo dynamic data tag. That difference is one reason registered tags suit team sites better than echo calls.
Where should the code for a custom tag go?
Use a small site plugin when the tags describe your data or business rules, because it survives theme changes. A Bricks child theme works when the tags belong to the design, and a code snippets plugin is fine for experiments. Do not edit the Bricks parent theme, because updates overwrite it. Keep whichever you choose in version control and give your tag names a unique prefix.
Why does my tag appear in the picker but print nothing on the page?
The picker hook only lists the tag. You also need the resolving filters: bricks/dynamic_data/render_tag for single tags and bricks/dynamic_data/render_content plus bricks/frontend/render_data for tags inside strings. Check that the registry key, the regular expression and the typed tag match exactly, and that your callback does not return an empty string because of an allow-list or missing data.
Why does my tag show the page data instead of the loop item?
Inside a query loop, Bricks resolves dynamic data against the current loop result and passes that post to your callback. If the callback reads the global post or calls get_the_ID, it describes the page instead. Always use the post argument that Bricks passes in. For loops over terms or users, check what your callback receives, because the item is not a post.
Can a custom tag take arguments?
Yes. The documented pattern is a colon followed by the argument, such as my_dd_tag:arg1, handled by splitting the tag string in your callback. Bricks also documents key-value arguments such as @fallback for core tags, but the guide for creating tags only shows the colon form, so log what reaches your callback before relying on key-value arguments. Always validate every argument.
How do I return an image from a custom tag?
Return an array whose first item is an attachment ID or an image URL when the context is image. The Bricks guide recommends an attachment ID when Bricks needs image size and srcset data. For link contexts return a URL string, and for text return a plain escaped string. Return an empty string when there is no image so the element can fall back.
What is the difference between render_tag and render_content?
The render_tag filter resolves one tag at a time and is where a custom tag's value is produced. The render_content filter, together with bricks/frontend/render_data, handles whole strings that may contain several tags and other text. A complete custom tag registers callbacks for both, usually by sharing one resolver function so the logic lives in one place.
Should I use the echo tag instead of writing a custom tag?
Use echo for a quick call to one existing PHP function on a site with trusted editors. It needs code execution enabled for the user, each function name allowed through the bricks/code/echo_function_names filter, single-quoted arguments and a function that returns its value. A custom tag avoids those permissions, appears in the picker and takes arguments, so it suits shared or client sites.
How do I cache an expensive tag?
Cache anything that runs queries beyond the given post or calls an external service. Use the object cache for per-request or persistent values and transients for values with a lifetime, with a hashed key and a sensible expiry. Remember that a full page cache stores the final HTML, so a tag that depends on time or the current user may need the page excluded from caching.
Is it safe to print custom field values from a tag?
Only if you escape and validate. Check any meta key named in an argument against an allow-list, validate types, and escape with esc_html, esc_attr or esc_url to match the output. Bricks passes text output through wp_kses_post by default, but that is a safety net, so escape in your own code too. Never reveal data from posts the visitor cannot read.
Will custom tags work in conditions and query settings?
Dynamic data is documented as usable in element conditions, custom attributes and several query settings, and a registered tag goes through the same replacement pipeline, so it should resolve there. Test each place you plan to use it, since a condition compares the rendered output and a query setting may need a number or date format your tag does not return by default.
Will my custom tags survive a Bricks update?
The hooks used here are listed in the Bricks documentation, which is a good sign, but they belong to a product that changes. Keep the code small and thin, keep a test matrix, and try each Bricks update on a staging copy first. If an extension point changes, a short plugin with a clear registry is easy to adjust.



