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

Extend Bricks Builder Query Loops With PHP: Custom Queries and Loop Objects

Go beyond the Bricks query controls: use the PHP query editor safely, adjust queries with documented filters, loop over arrays, cache with transients and sanitise input.

Written by
WPresident Editorial
Topic
Design and Builders

The Bricks query loop covers a great deal without any code. You can pick post types, taxonomies and meta conditions, sort by several fields, include or exclude posts using dynamic data, and save a configuration once as a reusable query. Then one day a requirement arrives that the controls cannot express: order posts by a score that combines comments, views and age; show only items the current visitor has not seen; list rows from an array your own function builds; or pull the loop’s arguments from a rule that lives in PHP. At that point you have a choice of ways to bring PHP into the loop, and the choice matters more than the code. A wrong choice leaves executable PHP stored in the database, tied to an element ID that changes when someone duplicates the element, and unsafe the moment it reads a value from the URL.

The single most important idea in this tutorial is that a Bricks query loop is a pipeline with named stages, and that you should step in at the earliest stage that solves the problem. The settings become query arguments. The arguments feed a query that runs. The result can be adjusted. Each iteration of the loop has a current object, and the elements inside read from it through dynamic data. Bricks documents hooks at several of these stages, plus a PHP query editor inside the builder. If the controls can do the job, use the controls. If you need computed arguments, a filter in your child theme or a small plugin is usually safer and easier to maintain than code inside the builder. If you need data that does not come from WordPress queries at all, such as an array or an API response, Bricks has dedicated query types for that, and a hook for registering your own.

This tutorial walks the pipeline from the front to the back. It starts with the stages and a decision rule for choosing between controls, the query editor, filters, array and API loops, and custom query types. It covers the editor and what Bricks requires before it will run your code, then the filters that adjust posts, terms and users queries, then the discipline of treating request input as hostile. After that it shows how to loop over your own arrays, how the loop object and its helper functions work, and which caching layers sit between a visitor and your database. The second half is a worked example: posts ordered by a computed score, cached with a transient, wired into one loop, invalidated sensibly and covered by a test plan, with the reasoning behind each decision.

A few honest boundaries. This is a general guide built from the public Bricks documentation, not a test report, and it contains no benchmark numbers. Hook names, argument lists and control names in this tutorial are the ones the documentation describes; where something is version-sensitive, or an exact name could not be confirmed, the text says so and tells you where to look in the Bricks documentation. Treat every snippet as an example to adapt: element IDs, field names, post types and cache durations are placeholders. Run everything on a staging copy first, and keep the query logic in version control.

You need to be comfortable reading PHP and the arguments of WP_Query. You do not need to know Bricks internals. What you need is the habit of asking, before each line of code, whether a control could have done this, and what happens when the input is empty, malicious or slow.

Key points

  • A Bricks query loop is a pipeline of settings, query arguments, query run, result and loop object; step in at the earliest stage that solves the problem.
  • Use the controls first, then a filter in version-controlled code, and use the PHP query editor only when its extra requirements (code execution, signatures, trusted users) are acceptable.
  • The documented filters for posts, terms and users receive the query arguments, the element settings and the element ID, so always guard on the element ID and always return the arguments.
  • Treat any value from the URL or a form as hostile: sanitise it, validate it against an allow-list, and never widen post status or capabilities because of it.
  • Arrays and API responses can feed loops through the Array and API query types, and custom object types can be added with the query run and loop object hooks.
  • Cache the expensive part, not the whole query: store a computed list of IDs in a transient, give it a key you can version, and keep the final query a cheap lookup by ID.

The query loop is a pipeline: where PHP can step in

Before adding any code, it helps to know the order in which Bricks does its work, because each stage has its own hook and its own risks. The Query Loop documentation describes five built-in query types: posts, terms, users, API and array. Posts, terms and users are backed by the WordPress query classes WP_Query, WP_Term_Query and WP_User_Query. The API and array types render items from JSON or from a PHP or JSON-style array. Everything else, including your own types, goes through hooks.

The pipeline looks like this. First, Bricks reads the settings of the loop element, the controls you filled in. For posts, terms and users it turns them into an array of query arguments, and this is the moment the three query_vars filters run: bricks/posts/query_vars, bricks/terms/query_vars and bricks/users/query_vars. Each receives the arguments array, the element settings, the element ID and the element name. Second, the query runs. For a custom query type this is the stage where the bricks/query/run filter supplies the results array that the loop will iterate over; Bricks documents it as the place to add query result types beyond posts, terms and users. Third, the result is adjusted. The bricks/query/result filter lets you modify the fetched results before the loop renders them, and companion filters adjust the result count and the maximum number of pages that pagination uses.

Fourth comes the loop itself. For each iteration Bricks makes one item the current loop object, and the filters bricks/query/loop_object, bricks/query/loop_object_id and bricks/query/loop_object_type let you manage what that object is, which ID Bricks reads from it and whether it counts as a post, a term or a user. Fifth, the elements inside the loop render, and dynamic data tags read from the current object: a post tag reads the current post, a term tag the current term, and so on. Two actions, bricks/query/before_loop and bricks/query/after_loop, let you set up and tear down state around the whole loop.

Two behaviors of this pipeline surprise people. The first is that every unique query is executed only once per page load, and its results are reused on the same page. The Bricks documentation lists the filters that this affects and notes that they may therefore not run multiple times: the three query_vars filters, the merge filter, and the query run, result, result count and max pages filters. There is a force-run filter for the cases that need a fresh execution, and the documentation also describes a bricks_force_run key you can set in the arguments. The practical consequence is that your hooks must be free of side effects. Never count calls, never write to the database from inside a query filter, and do not assume a filter fires once per element on the page.

The second surprise is that the filters apply to every loop, not only yours. A callback registered on bricks/posts/query_vars runs for the posts, products and query loop elements on every page that renders one, so it must identify its target. The documented pattern is to compare the element ID, a six-character string. In the Query Loop documentation the target query ID is described as the loop element’s ID without the #brxe- prefix, so a loop whose selector is #brxe-abc123 has the ID abc123. Everything in this tutorial uses abc123 as that placeholder.

Stages of a Bricks query loop and the hooks at each one

  1. Loop settingsControls on the loop element, or the query editor code.
  2. Query arguments builtbricks/posts, terms and users /query_vars filters.
  3. Query runsWP_Query, WP_Term_Query, WP_User_Query, or bricks/query/run for custom types.
  4. Result adjustedbricks/query/result, result_count and result_max_num_pages.
  5. Loop object per itembricks/query/loop_object and its id and type siblings.
  6. Elements renderDynamic data tags read the current loop object.
The order in which a loop is built and rendered, with the documented extension point at each stage.

Use the controls first: a decision rule for choosing the PHP route

The most maintainable PHP is the PHP you did not write, and the Bricks controls have grown to cover many cases that used to need a filter. Check the list before you open an editor. The posts query supports multiple order by criteria with their own directions, so “popularity first, then date” no longer needs code. The documentation notes that when you order by several criteria and paginate, you should add the post ID as a final tie-breaker, otherwise posts with equal values may appear on more than one page. Meta queries can compare custom fields, and the documentation gives a worked note on ACF date fields: a meta query compares the stored database value, which for an ACF Date Picker is stored as Ymd whatever the display format, so a comparison against {current_wp_date:Ymd} with a numeric type returns upcoming items.

The include and exclude controls for posts accept dynamic data, so IDs stored in a relationship, post object or gallery field of the supported field plugins can feed the loop without PHP; the documentation points out that the post type must match the values, for example Media for gallery images. A loop can exclude the current post, restrict itself to terms of the current post, and turn off query merge when it is not the main query of an archive. Performance controls such as No Found Rows and disabling meta and term cache updates are also available in the interface. And when you need the same configuration in several places, a Global Query stores it once and each loop references it, which is the reuse mechanism to reach for before copying PHP.

When the controls truly cannot express the logic, pick the route by asking what is missing. If the arguments need a value computed in PHP, such as a list of IDs from a ranking function, a lookup in a custom table or a decision based on the current user, adjust the arguments with the query_vars filter, or with the query editor if you accept its requirements. If the arguments are fine but the fetched results need rearranging or trimming, use the result filter. If the data is not in the WordPress database, use the Array or API query type: the Array type loops over any PHP or JSON array, and the API type fetches JSON from a URL, both documented in the Query Loop article. If you need something stranger, a different kind of object with its own rules, register a custom query type with the query run and loop object hooks.

Two limits shape this choice. First, Query Filters and Live Search work on post, term and user loops, but the documentation states they do not target API or array loops. If you need faceted filtering over external data, sync it into WordPress instead. Second, the Results Filter feature of the Array and ACF Repeater loops lets you drop items by condition from the interface, and its rules combine with AND logic; the documentation points to the bricks/query/result hook when you need more complex conditions. The decision figure below turns this reasoning into a rule you can apply quickly.

Which route fits the requirement?

What can the built-in controls not do for this loop?
Nothing: the controls and a Global Query cover itStay in the interface; no PHP to maintain.
Arguments need a value computed in PHPAdjust them in a query_vars filter, or in the query editor if its requirements are acceptable.
Fetched results need rearranging or trimmingUse the bricks/query/result filter, and keep count and page metadata consistent.
The data is an array or an API responseUse the Array or API query type; a custom query type is the last resort.
A rule for choosing between controls, filters, result handling, Array or API loops and custom query types.

The PHP query editor: what Bricks requires before it runs your code

The Query editor (PHP) is a control on the loop element. Once you turn it on, a code editor appears in which you write PHP that returns an array of WordPress query arguments. The documentation says the editor supports dynamic data, so a value such as a date tag can appear inside the code. It is the most flexible route and also the one with the heaviest requirements, which are there for good reason: it stores executable PHP in the site’s data.

Bricks guards this in layers. Code execution must be enabled in the Bricks settings under Custom code, and it is off by default. On top of the global switch, the user must hold the execute code capability, granted per role or per individual user, and the documentation advises granting it only to people you trust completely, preferring per-user grants over role-based ones. Then there are code signatures. When you save query editor code, it must be signed; Bricks hashes the code with a WordPress function and stores the signature, and if the saved code is later changed without being signed again, Bricks refuses to run it. In the builder, elements with unsigned code are highlighted, and a Sign code action sits above the editor. The Bricks settings also provide a Code review tool that lists every instance of Code elements, SVG code, query editor code and echo tags with their signature status, which is worth running before and after any site migration or change to the WordPress secret keys, since signatures are derived from them.

The editor’s contract is narrow, and the documentation says so directly: keep the returned array focused on query arguments, do not echo output, and do not run unrelated database writes. A reasonable example is a loop of upcoming events, written as plain arguments:

return [
	'post_type'           => 'event',
	'posts_per_page'      => 6,
	'ignore_sticky_posts' => true,
	'no_found_rows'       => true,
	'meta_key'            => 'event_date',
	'orderby'             => 'meta_value_num',
	'order'               => 'ASC',
	'meta_query'          => [
		[
			'key'     => 'event_date',
			'value'   => wp_date( 'Ymd' ),
			'compare' => '>=',
			'type'    => 'NUMERIC',
		],
	],
];

This returns events whose stored date is today or later, soonest first, six at a time. The field name event_date and the post type are placeholders, and the comparison assumes an ACF-style date stored as Ymd, as the Bricks documentation describes. wp_date( 'Ymd' ) formats the current date in the site’s timezone, so “today” follows your site settings rather than the server clock. no_found_rows skips the count query that pagination needs, which is right for a fixed list of six. Check the editor’s default content in your version for the exact way it expects the code to be written, since the starting text shows the convention.

Be deliberate about where you use it. A global query can hold query editor code, and the documentation warns that editing that code affects every loop using the query. Use a global query for PHP only when centralisation is worth that blast radius. The editor code also lives in the database, outside version control, so for anything non-trivial the usual advice applies: put the logic in a function inside your child theme or a small site plugin, and keep the editor to a one-line call of it. That way the real code is reviewed, versioned and tested like any other code, and the editor holds only a pointer.

Query editor or a PHP filter

Query editor (PHP)Filter in theme or plugin
Where the code livesIn the builder data, in the databaseIn a file you can review and version
Code execution switchMust be enabled in settingsNot involved
SignatureRequired and checked on every runNot applicable
Who can change itUsers with the execute code capabilityWhoever can deploy code
Targets the loop byBeing attached to that elementThe element ID inside the callback
When an element is duplicatedThe code is copied with itThe copy has a new ID and is not matched
How the two ways of running PHP for a loop differ on the points that matter for safety and maintenance.
Rendered output of the code above
Two lists side by side. On the left, seven events with their stored dates in Ymd form, two of them in the past and greyed out. On the right, the five upcoming events in the loop, ordered from the soonest date to the latest.
A plain HTML and CSS render of what the upcoming-events arguments return from seven made-up sample events, not a screenshot of the Bricks editor.

Adjust query arguments with the documented filters

For posts and products loops the hook is bricks/posts/query_vars. It runs after Bricks has turned the loop settings into an array of WP_Query arguments and before the query is performed. According to the documentation the callback receives four values: the arguments array, the settings array holding the element settings from the builder, the element ID as a string, and the element name. Terms and users loops have the same shape with bricks/terms/query_vars and bricks/users/query_vars, feeding WP_Term_Query and WP_User_Query. Because these run for every loop of their kind on every page, the pattern is always the same: identify your loop, change what you need, return the array.

Rather than scattering one anonymous function per loop, use a single dispatcher that maps element IDs to named handler functions. When someone duplicates a loop, the new element has a new ID, and you only need to add one line to the map. Put this in your child theme’s functions.php or in a small site plugin:

function wpr_query_handlers() {
	return array(
		'abc123' => 'wpr_query_trending',
		'def456' => 'wpr_query_same_author',
	);
}

add_filter( 'bricks/posts/query_vars', function ( $query_vars, $settings, $element_id ) {
	$handlers = wpr_query_handlers();

	if ( ! isset( $handlers[ $element_id ] ) || ! is_callable( $handlers[ $element_id ] ) ) {
		return $query_vars;
	}

	return call_user_func( $handlers[ $element_id ], $query_vars, $settings );
}, 10, 3 );

function wpr_query_same_author( $query_vars, $settings ) {
	$author_id = (int) get_the_author_meta( 'ID' );

	if ( $author_id < 1 ) {
		$query_vars['post__in'] = array( 0 );
		return $query_vars;
	}

	$query_vars['author']              = $author_id;
	$query_vars['post__not_in']        = array( (int) get_the_ID() );
	$query_vars['ignore_sticky_posts'] = true;

	return $query_vars;
}

The dispatcher registers one callback and asks for three of the four arguments, which is allowed: WordPress passes only as many as you request. It looks up the element ID in the map and returns the arguments untouched when the loop is not listed, so every other loop on the site is unaffected. The example handler restricts a loop to other posts by the current post’s author. The element names abc123 and def456 and the function names are placeholders; replace the IDs with the six-character IDs of your own loops.

A handful of rules keep these filters out of trouble. Always return the array, even when you did nothing; a callback that returns nothing leaves the loop with no arguments. Change specific keys instead of replacing the whole array, so the settings the editor chose in the interface still apply. Remember that your filter runs after the settings were translated, so a value you set overrides whatever the controls produced, including orderby. Treat an empty post__in with care: in WP_Query an empty list means “no restriction”, so a loop that should show nothing would instead show everything. The Bricks documentation examples set it to an array containing zero for exactly this reason, which matches no post. When you are modifying the arguments of a WooCommerce products loop, the documentation advises a higher priority such as 20 or 30, because other code hooking the same filter may otherwise overwrite your change.

Terms and users follow the same recipe. The documentation shows excluding the current term from a terms loop on a term archive page by setting the exclude argument to the queried object ID, and limiting a terms loop to the terms attached to a post by setting object_ids. Those are two lines each, guarded by the element ID, and they are good models for your own. For secondary loops in headers, footers and sidebars, remember the merge behavior: on archive and search templates Bricks merges a loop’s query with the main query unless you disable query merge, so a loop that should be independent needs that setting or the bricks/posts/merge_query filter, which receives a boolean and the element ID.

The figure below shows what the same-author handler does to a pool of posts. It is built from made-up sample data and lists, for each post, whether the loop keeps it and which argument decided.

Rendered output of the code above
A table of six sample posts with their author and a verdict. Posts by Author A are kept, except the current post which is dropped by the exclude-current-post argument. Posts by Author B and Author C are dropped by the author argument.
A plain HTML and CSS render of which sample posts survive the same-author arguments, not a screenshot of the Bricks editor.

Never trust request input: sanitise, validate, allow-list

The moment a query argument comes from the URL, a form or an AJAX call, your query code becomes a security boundary. The risks are specific: someone supplying an unexpected value to change what the loop returns, to reveal content that should be private, to make the query slow, or, if you build SQL by hand, to inject SQL. The defenses are also specific, and they are the same ones you would use in any WordPress code.

Take a loop that can be narrowed by a topic query parameter, such as a link ending in ?topic=guides. The safe version reads the value, sanitises it, and then checks it against what actually exists rather than trusting its shape:

function wpr_requested_topic() {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only filter, no state change.
	$raw = isset( $_GET['topic'] ) ? wp_unslash( $_GET['topic'] ) : '';

	if ( ! is_string( $raw ) || '' === $raw ) {
		return '';
	}

	$slug = sanitize_key( $raw );

	if ( '' === $slug || ! term_exists( $slug, 'category' ) ) {
		return '';
	}

	return $slug;
}

function wpr_query_topic( $query_vars, $settings ) {
	$topic = wpr_requested_topic();

	if ( '' !== $topic ) {
		$query_vars['category_name'] = $topic;
	}

	return $query_vars;
}

Walk through it line by line. wp_unslash removes the slashes WordPress adds to request data. The is_string check rejects array-shaped input such as ?topic[]=x, which would otherwise cause type errors. sanitize_key reduces the value to lowercase letters, numbers, dashes and underscores. Then term_exists is the allow-list step: only a slug that is a real category passes, so unknown values are ignored, not passed into a query. The handler sets category_name, which takes a slug, and does nothing otherwise, so a bad value degrades to the unfiltered loop. Register wpr_query_topic in the dispatcher map from the previous section. Numbers follow the same pattern: use absint and clamp to a sensible range, so that ?per_page=99999 cannot ask for a huge page.

A few related rules complete the picture. Never let request data widen visibility: do not pass a status from the URL into post_status, do not let a parameter add private post types, and do not build capability decisions from user input. If you ever need raw SQL, use $wpdb->prepare with placeholders and esc_like for wildcard searches, but prefer the query classes, which already do this. Keep the editor and the filters free of output: no echo, no var_dump left behind from debugging. And escape at output, not in the query; the loop’s elements and tags decide how values are printed, so check what your tags emit instead of assuming.

Two practical consequences of URL-driven loops deserve attention. First, caching: a page whose loop varies by query string either needs a page cache that treats the query string as part of the key, or must be excluded from caching, and any transient you build must include the sanitised parameter in its key, otherwise one visitor’s choice is served to everyone. Second, Bricks features that re-run queries in the background. Load more, infinite scroll and AJAX pagination make separate requests, so a filter that reads the page URL may see different input in them than on the first render. Test every URL-driven loop through each of those, and consider passing state through a mechanism the documented Bricks features support, such as query filters, instead of hand-rolled parameters.

The figure below walks six sample requests through the topic code from earlier in this section, on a made-up site whose only categories are guides and news. Notice that every value that is not a real category ends the same way, as the unfiltered loop.

Rendered output of the code above
A table of six example topic requests. Guides and Guides in capitals both become the slug guides and filter the loop. A category that does not exist, an array-shaped value, an injection-style string and an empty value are all ignored, leaving the loop unfiltered.
A plain HTML and CSS render of six sample requests and how the sanitise-then-allow-list code treats each, not a screenshot of the Bricks editor.

Looping over your own arrays and API responses

Not every loop needs WordPress to be the data source. The Array query type loops over any PHP or JSON array and supports the same pagination features as other loops, including AJAX pagination, load more and infinite scroll. The API query type fetches JSON from a URL, extracts an array from the response and renders one loop item per element. The full API workflow, including caching and security, is the subject of the companion tutorial on the REST API; here the focus is what PHP adds.

The documented way to feed the Array type from PHP is the echo dynamic data tag. In the Array editor of the loop you write a tag such as {echo:my_custom_array()}, and Bricks calls your function and loops over what it returns. Two gates apply. Code execution must be enabled in the Bricks settings, and since a security change in Bricks the function name must be allowed explicitly through the bricks/code/echo_function_names filter. The documentation states that you can return an array of exact names, or patterns that start with an at sign, and it also describes returning a boolean from your own check. Keep the list short and specific.

add_filter( 'bricks/code/echo_function_names', function () {
	return array(
		'wpr_opening_hours',
	);
} );

function wpr_opening_hours() {
	$hours = array(
		array( 'day' => 'Monday to Friday', 'time' => '09:00 to 17:30' ),
		array( 'day' => 'Saturday',         'time' => '10:00 to 14:00' ),
		array( 'day' => 'Sunday',           'time' => 'Closed' ),
	);

	return array_map( function ( $row ) {
		return array(
			'day'  => sanitize_text_field( $row['day'] ),
			'time' => sanitize_text_field( $row['time'] ),
		);
	}, $hours );
}

The first block is the allow-list. Following the documentation’s own example, the callback returns the exact function names Bricks may call from an echo tag; if several snippets each need an allowed function, keep all the names in one array in one place, since each callback’s return value stands alone. The second block is the function itself. It returns a list of associative arrays, one per loop item, and passes each value through sanitize_text_field so that the data is clean at the source, whatever the later output stage does. In a real site the rows would come from an option, a settings screen or a custom table; hard-coding them here keeps the example short.

On the loop element, set the query type to Array, put {echo:wpr_opening_hours()} in the Array editor, and inside the loop use the array tag with a key: {query_array @key:'day'} and {query_array @key:'time'}. For a flat list of strings, {query_array} on its own outputs the current value. Arrays inside arrays can be looped by nesting another Array loop inside the first and entering {query_array @key:'name_of_inner_key'} in its Array editor. The Results Filter, available for Array and ACF Repeater loops, can then drop items by condition after the array is fetched, with rules combined by AND.

Two cautions. The array loop type does not support Query Filters or Live Search, so do not promise visitors a search box over it. And your function runs on every render of the page, so anything slow inside it, a remote request or a heavy query, needs the caching described in the performance section below. If your data comes from an API you do not control, you can also adjust the request Bricks makes: the documentation lists filters on the API query for request arguments such as the timeout, headers and body, and an action that runs after the response arrives so you can log errors. Secrets for the API type belong in PHP constants rather than in the builder, as the documentation recommends.

The figure shows the data the opening-hours function returns beside the markup a loop over it could produce, with one list item for each array row and the two keys printed in the places the query_array tags go.

Rendered output of the code above
On the left, the three rows of the opening hours array with their day and time keys. On the right, a card titled Opening hours that lists Monday to Friday 09:00 to 17:30, Saturday 10:00 to 14:00 and Sunday Closed, one row per array item.
A plain HTML and CSS render of the three-row array and the list a loop over it could print, not a screenshot of the Bricks editor.

The loop object: what the current item is, and how to hook into it

Inside a loop, every dynamic data tag answers the question “current what?” The answer is the loop object, the item of the current iteration. For a posts loop it is a WP_Post, for terms a WP_Term, for users a WP_User, and for Array and API loops an item of the array, which is why those loops use the dedicated {query_array} and {query_api} tags with a key. The Query Loop documentation adds a limit worth knowing: in a nested loop the inner result becomes the current result, and Bricks has no parent-loop syntax for output tags, so values belonging to the parent have to be kept outside the inner loop, or read through custom PHP or a custom dynamic data tag.

For PHP that needs to know where it is, Bricks documents a small set of static helpers. \Bricks\Query::get_loop_object_id() returns the ID of the current iteration’s object, and by default the ID comes from the object when it is a WP_Post, WP_Term or WP_User. \Bricks\Query::get_loop_object_type() returns the object type, which the documentation says can only be post, term or user. \Bricks\Query::get_query_object_type() takes a query ID and returns the type of that query. Community snippets also use a static accessor that returns the whole current object; it is not described in the public documentation, so check the source of your installed version before relying on it, or capture the object yourself in a hook, as shown below.

The three loop object filters give you control. bricks/query/loop_object receives the current object, the loop key and the query object on every iteration, so you can prepare state, for example setting the global post and calling setup_postdata, as the documentation’s comments suggest. bricks/query/loop_object_id lets you change which ID Bricks reads from the object, and bricks/query/loop_object_type lets you declare the object a post, term or user. The documentation’s own example treats the items of a WooCommerce cart query as posts inside each iteration, which makes every post and product tag work on them. That trick is the key to custom types: if your items are WP_Post objects, declare them posts and the existing tags just work.

A custom query type then needs three pieces. A filter on bricks/query/run returns the results array for your type, after checking the query object’s type so that it ignores every other loop. A filter on bricks/query/loop_object prepares each item. And the type must appear in the Query control’s type list, which the documentation says is done through the bricks/setup/control_options filter that manages the options for things such as query types. The documentation’s example for that filter adds a template type, so look up the option key for query types in the current documentation instead of guessing it.

add_filter( 'bricks/query/run', function ( $results, $query_obj ) {
	if ( 'wpr_rows' !== $query_obj->object_type ) {
		return $results;
	}

	return wpr_opening_hours();
}, 10, 2 );

add_filter( 'bricks/query/loop_object', function ( $loop_object, $loop_key, $query_obj ) {
	if ( 'wpr_rows' !== $query_obj->object_type ) {
		return $loop_object;
	}

	wpr_remember_current_row( $loop_object );

	return $loop_object;
}, 10, 3 );

The first filter answers only for the placeholder type wpr_rows and returns whatever array your function builds; the loop iterates it. The second runs on each iteration for that type and hands the current item to a helper of yours, wpr_remember_current_row, which would store it in a static variable so other functions, such as an echo function used inside the loop, can read it without any undocumented accessor. Those helper names are yours to define. For plain arrays, the Array type with the echo tag is simpler and needs no registration; reserve custom types for cases where you need your own object type or want the loop to behave like a first-class query.

After the fetch, the result filter is the place for post-processing. For a native posts loop it receives a WP_Query object, for an ACF loop it can be an array, so check the type and the element ID first. The documentation’s example re-sorts a post result by title in PHP. Its warning is the important part: slicing or reordering results does not recalculate the total count, the maximum number of pages or summary positions, so a loop with pagination or a results summary needs the count and max pages filters kept consistent, and for ordinary limits and offsets you should use the loop’s own controls.

What the current loop object is, by query type

Loop objectRead it with
PostsA WP_PostPost tags such as post_title
TermsA WP_TermTerm tags such as term_name
UsersA WP_UserUser tags such as wp_user_display_name
ArrayOne array itemquery_array, with a key for associative items
APIOne item of the response arrayquery_api, with a key; pipe separates nested keys
Custom typeWhatever your run filter returnsDeclare it a post, or use your own function or tag
The object each query type puts in the current iteration, and the dynamic data that reads it.

Performance: the caching layers between a visitor and your database

A query loop that is fast on a developer’s laptop can be slow in production for ordinary reasons: more rows, no object cache, a meta query that scans a large table, or a ranking function that loops over hundreds of posts. Before adding your own cache, know what already exists, because stacking caches without understanding the others is how stale content happens.

From the visitor inward, the first layer is the full-page cache, whether from a plugin, the host or a CDN. When it hits, none of your PHP runs. Everything below only matters on a miss. The second layer is inside Bricks: each unique query runs once per page load and its results are reused on the same page, so a loop repeated in a template does not query twice. The third is a Bricks setting called Cache query loops in the Performance settings. It caches query loop results in the WordPress object cache, with a key built from the element ID, the query arguments and the parent loop context. The documentation notes that for the cache to persist across page loads you need a server-level object cache such as Redis or Memcached, and that you should turn it off if you see stale or unexpected results. A filter, bricks/query/cache_key, lets you vary the key by external context such as the current language.

The fourth layer is yours: a transient or object cache entry holding something expensive you computed. The fifth is the database. This is where the interface’s performance options pay off: No Found Rows skips the pagination count when you do not need it, the options that disable post meta and term cache updates help when the loop does not use that data, and a realistic posts per page matters, with minus one avoided on large datasets, as the Bricks guidance says. Also add a stable secondary sort when you paginate.

When you add your own cache, a few principles keep it honest. Cache the expensive part and leave the cheap part live. A ranking function that scans two hundred posts is worth caching; the final lookup of twelve posts by ID is not, and leaving it live means edits to titles and images show immediately. Cache identifiers rather than objects: a list of IDs is small, and WordPress’s own object caching handles the posts. Give every cache a bounded lifetime so a missed invalidation heals itself, and put a version in the key so that you can invalidate everything by bumping one number. Make the key depend on every input that changes the result, such as the limit, the language or the sanitised URL parameter, and on nothing else, which would fragment the cache.

Know what a transient is. On a site with a persistent object cache, WordPress stores transients there, in memory, and they may disappear at any time when memory is reclaimed. On a site without one, transients live in the options table, and expired ones are only cleaned up as they are read or by a scheduled task. Either way a transient is a cache, never storage: your code must work when it is gone. Finally, guard against a stampede: when a popular cache entry expires, many requests may recompute it at once. For a cheap computation ignore this. For an expensive one, add a short lock transient so one request recomputes while the others serve slightly old data, or schedule the recomputation with WP-Cron and let requests read only.

Cache layers between a visitor and the database

Page cache or CDNServes stored HTML; your PHP does not run on a hit.
One run per unique query per pageBricks reuses results within a single page load.
Cache query loops settingObject cache entry keyed by element ID and query arguments.
Your transient or object cache entryThe expensive computed part, with a TTL and a versioned key.
Database lookupsWP_Query and meta reads; trim with no found rows and smaller pages.
Each layer answers before the one below it; your own transient sits next to the Bricks layers and must agree with them.

Worked example, part one: a score for every candidate post

The requirement: a “Trending” loop that shows twelve posts ordered by a score instead of by date. The score combines comment count, a view counter and age, so a post with lots of recent engagement outranks a newer quiet one. The Bricks query controls cannot compute this, because the score is not a stored field you can sort by. The design below has three parts: a function that computes the ranked list of IDs, a transient that caches it, and a filter that gives the list to one loop. This section builds the first two.

The design decisions come before the code. The score is computed only over recent posts, so the candidate set is bounded and a ranking run is cheap enough to repeat every few minutes. The function returns IDs in order and nothing else. The result is cached for fifteen minutes, because trending lists do not need to be real time and fifteen minutes cuts the work to a small fraction of the requests. The cache key includes a version number that any publish or delete event can bump. The formula divides engagement by a power of age, a standard time-decay shape, so scores fall smoothly rather than dropping off a cliff. The view counter is assumed to be a numeric custom field named wpr_view_count that your site already maintains; replace it with any signal you trust, or remove it.

function wpr_ranked_post_ids( $limit = 12 ) {
	$limit   = max( 1, min( 50, absint( $limit ) ) );
	$version = (int) get_option( 'wpr_ranked_version', 1 );
	$key     = 'wpr_ranked_' . $limit . '_v' . $version;

	$cached = get_transient( $key );
	if ( is_array( $cached ) ) {
		return $cached;
	}

	$candidates = get_posts( array(
		'post_type'           => 'post',
		'post_status'         => 'publish',
		'posts_per_page'      => 200,
		'orderby'             => 'date',
		'order'               => 'DESC',
		'date_query'          => array( array( 'after' => '90 days ago' ) ),
		'fields'              => 'ids',
		'no_found_rows'       => true,
		'ignore_sticky_posts' => true,
	) );

	$rows = array();

	if ( $candidates ) {
		update_meta_cache( 'post', $candidates );
		$now = time();

		foreach ( $candidates as $post_id ) {
			$age_days = max( 0, ( $now - (int) get_post_time( 'U', true, $post_id ) ) / DAY_IN_SECONDS );
			$comments = (int) get_comments_number( $post_id );
			$views    = (int) get_post_meta( $post_id, 'wpr_view_count', true );

			$rows[] = array(
				'id'    => (int) $post_id,
				'score' => ( ( $comments * 5 ) + $views ) / pow( $age_days + 2, 1.5 ),
			);
		}
	}

	usort( $rows, function ( $a, $b ) {
		$by_score = $b['score'] <=> $a['score'];
		return 0 !== $by_score ? $by_score : $b['id'] <=> $a['id'];
	} );

	$ids = array_map( 'intval', wp_list_pluck( array_slice( $rows, 0, $limit ), 'id' ) );

	set_transient( $key, $ids, 15 * MINUTE_IN_SECONDS );

	return $ids;
}

Reading it in order: the limit is clamped to a safe range with absint, so the function cannot be asked for an enormous list. The key combines the limit and the version. A cache hit returns immediately, and is_array matters: an empty list is a valid cached answer, which a simple truthiness check would treat as a miss and recompute on every request. The candidate query fetches only IDs, for published posts from the last ninety days, at most two hundred, without the count query. update_meta_cache loads all the custom field values for those posts in one query, so the loop does not read each one separately. The score is engagement over a decaying age; adding two days to the age keeps brand-new posts from dividing by nearly zero. The sort uses the spaceship operator and breaks ties by ID, so equal scores always come out in the same order, which keeps pagination stable. The final lines trim to the limit, store the IDs and return them.

To see the formula at work, take five made-up posts and do the sums by hand, as the figure does. Engagement is five times the comment count plus the views. The divisor is the age in days plus two, raised to the power of 1.5. The score is the first divided by the second, and the bar is scaled to the highest score in the sample.

Rendered output of the code above
A table of five sample posts showing engagement, age in days, the age divisor and the resulting trending score with a horizontal bar. The one-day-old post scores highest at 454 and the nine-day-old post lowest at 86.
A plain HTML and CSS render of the ranking formula worked through on five made-up posts, not a screenshot of the Bricks editor.

Worked example, part two: wire the ranking into one loop and keep it fresh

The ranked list is only useful once a loop uses it. The handler below receives the arguments Bricks built for the Trending loop and replaces the ordering. It is registered in the dispatcher map from earlier, so the entry 'abc123' => 'wpr_query_trending' connects it to the loop whose element ID is abc123.

function wpr_query_trending( $query_vars, $settings ) {
	$ids = wpr_ranked_post_ids( 12 );

	if ( empty( $ids ) ) {
		// An empty post__in would mean "no restriction", so match nothing instead.
		$query_vars['post__in'] = array( 0 );
		return $query_vars;
	}

	$query_vars['post_type']           = 'post';
	$query_vars['post__in']            = $ids;
	$query_vars['orderby']             = 'post__in';
	$query_vars['ignore_sticky_posts'] = true;

	return $query_vars;
}

function wpr_bump_ranked_version() {
	update_option( 'wpr_ranked_version', time(), false );
}

add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) {
	if ( 'post' !== $post->post_type ) {
		return;
	}
	if ( 'publish' === $new_status || 'publish' === $old_status ) {
		wpr_bump_ranked_version();
	}
}, 10, 3 );

add_action( 'deleted_post', 'wpr_bump_ranked_version' );

On the Bricks side, add a container, enable Use Query Loop, keep the type on posts, and give the loop a posts per page value no larger than the twelve IDs the ranking returns. Inside the loop use ordinary post tags. The filter does the rest: it sets post__in to the ranked IDs and orderby to post__in, the standard WP_Query way of preserving the order of an ID list. Because the final query is a lookup by ID, titles, images and statuses are always live; only the ranking is cached. A post that was trashed since the last ranking simply drops out of the result, since the query only returns posts the visitor may see, so the list is briefly shorter instead of broken.

The invalidation code bumps the version number when a post of this type is published, unpublished or deleted. Changing the number changes the cache key, so the next request recomputes, and the old transient is left to expire on its own. Comments and view counts change constantly, and the fifteen-minute lifetime handles those. The option is saved without autoload, so it does not add to the data WordPress loads on every request. Remember the guideline from the pipeline section: nothing in these hooks writes anything because of a page view, only because of an editorial event.

Several alternatives deserve a mention, because the right choice depends on the site. If the ranking is expensive, compute it in a scheduled WP-Cron event and let the filter only read the stored list, which removes any chance of a visitor paying for the recomputation. If the score depends on the current visitor, such as personal reading history, a shared transient is wrong; cache per user, or do the personalization client-side after serving a generic list. If you prefer to keep this logic inside the builder, a query editor on the loop can return the same arguments by calling wpr_ranked_post_ids from the code field, under the code execution and signature rules covered earlier. And if the site has a persistent object cache, the Bricks setting that caches query loops adds a layer on top, so test freshness with both in place.

What the visitor sees is the point of the exercise. The figure shows a plain HTML and CSS render of the kind of list this produces, using made-up sample data to illustrate the ranking: older posts with strong engagement can outrank newer quiet ones, which is exactly what ordering by date cannot do.

Rendered output of the code above
A numbered list of five article titles ordered by a trending score computed from comments, views and age, with the score shown on the right of each row
A plain HTML and CSS render of a score-ordered list built from made-up sample data and the formula in the code above, not a screenshot of the Bricks editor.

A test plan for the worked example

A ranking function is easy to write and easy to get subtly wrong, and caching adds a second axis of things that can go wrong. A short test plan, run on a staging copy, catches most of the problems before visitors do. None of it needs special tooling: WP-CLI, the browser and a handful of test posts are enough.

Start with fixtures. Create five or six posts with known comment counts, known values in the view-count field and known publish dates, including two with identical scores. Work out the expected order by hand with the formula, then ask the function. WP-CLI can run it directly and show the cache state:

$ wp eval 'print_r( wpr_ranked_post_ids( 5 ) );'
$ wp option get wpr_ranked_version
$ wp transient get wpr_ranked_5_v1
$ wp transient delete wpr_ranked_5_v1

The first command prints the ranked IDs, which you compare with your hand calculation. The second shows the current version number, which you need to build the key. The third reads the cached list for a limit of five, and the fourth deletes it so the next call recomputes. One caution: on a site with a persistent object cache, the command line and the web server may not share the same cache, so a value you delete from the shell might still be cached for web requests. Confirm which cache each uses on your host.

Then test behavior, one property at a time. Cold and warm: call the function twice and confirm that the second call returns without running the candidate query; defining the SAVEQUERIES constant on staging lets you inspect the queries WordPress ran, or use any query profiler. Empty state: temporarily narrow the date window so no posts qualify and confirm the loop shows its no-results content rather than all posts; this verifies the zero-ID safeguard. Invalidation: publish a post, unpublish another, and confirm that the version changes and the list updates before fifteen minutes pass. Pagination and ties: set posts per page below the list length, move through the pages, and confirm that no post repeats and none is skipped, including the two posts with equal scores.

Next, test the wiring. Duplicate the loop and confirm the copy does not use the ranking until you add its new ID to the map, then confirm that the original still does; this proves the filter is keyed to the element. Check a few unrelated loops on other pages to confirm their arguments are unchanged. Test as a visitor and as a logged-in administrator, with the page cache on, to confirm that private or draft content never appears for visitors. If the loop is reachable through AJAX pagination or load more, test those paths too, since they make separate requests.

Finally, test failure. Delete the view-count field from one post and confirm the cast handles it as zero. Make the candidate set large on staging to see how long a cold computation takes, and decide from the result whether to move it to a scheduled event. Record what you checked and the date, so that the next person to change the formula knows what to retest. Without numbers from your own site, any claim about speed is a guess; measure on your hardware, with your data.

Test plan order for the trending loop

FixturesCreate known posts, work out the expected order by hand and compare with the function.
Cold and warmCall twice; the second call must be served from the transient.
Empty stateRemove all candidates and confirm the loop shows no results, not everything.
InvalidationPublish, unpublish and delete posts; the version and the list must update.
PaginationPage through the loop and check for duplicates, gaps and tie ordering.
Wiring and accessDuplicate the loop, test other loops, test logged out and with the page cache on.
A sequence for checking the ranking, the cache and the wiring, from the function outward.

Symptoms and causes: what usually goes wrong

Custom query code fails in a small number of recurring ways. Use this list as a first guess when a loop misbehaves, then confirm by logging or by inspecting the arguments.

The filter has no effect. The first suspect is the element ID. IDs are six characters, they differ between a loop and its duplicate, and they differ between a template and a page copy of the same layout. Confirm the ID against the loop’s element in the builder. The second suspect is registration: the code lives in a child theme that is not active, in a snippet that only runs in the admin, or in a file with a syntax error that stopped everything after it. Turn on debug logging on staging and read the log. The third suspect is the pipeline: remember that each unique query runs once per page load, so a filter may seem not to fire repeatedly, and the documentation describes a force-run filter and an argument key for the cases that need fresh execution.

The loop shows every post when it should show a few. This is almost always an empty post__in. Return an array containing zero when you want no results. Similar traps exist with empty author__in and tax_query arrays, so guard emptiness explicitly instead of relying on how WordPress reads an empty list.

The loop shows nothing. Check, in order: whether the ranking function returned an empty list, whether the date window or a meta condition excludes everything, whether the settings in the interface add a condition that conflicts with yours, and whether the cached value is an old empty list. Deleting the transient, or bumping the version, tells you quickly. If the loop is on an archive, check the main-query settings: the Bricks troubleshooting notes say that on archives you should enable Is main query for the main listing, and enable Disable Query Merge for unrelated loops.

Results are stale. List the layers: the page cache, the Bricks setting that caches query loops, your transient and the object cache. Purge them from the outside in, one at a time, and see which one clears the problem. A stale list after publishing usually means the version bump did not run, or a persistent object cache is serving the old option value. Pagination that shows a 404 on an archive, or repeated posts on the next page, usually means the loop is not marked as the main query where it should be, or the ordering has no stable tie-breaker, which the Bricks documentation advises adding when you order by more than one criterion.

Code in the query editor does not run. Bricks does not run it if code execution is disabled, if your user lacks the execute code capability, or if the signature is missing or invalid. Editing the code after signing invalidates the signature until you sign again; changing the WordPress secret keys invalidates every signature. The Code review tool in the Bricks settings shows each instance’s signature status. An echo function that fails is a different cause: the function name is not on the allowed list from the bricks/code/echo_function_names filter.

Finally, a site-level failure: one typo in a functions file can take the whole site down. Keep query code in a separate file, load it with a guard, work on staging, and prefix every function and option name so nothing collides with a plugin. A short file with a clear name and a header comment about its purpose is easier to disable in an emergency than a hundred lines buried in a theme file.

Checklist

  • Confirm that the built-in controls, including multiple order by criteria, meta queries, dynamic-data includes and a Global Query, genuinely cannot do the job before writing PHP.
  • Prefer a documented filter in a child theme or site plugin over the Query editor (PHP), so the code is reviewed and versioned.
  • If you use the Query editor, enable code execution only for trusted users, sign the code after every edit, and run the Code review tool before and after migrations.
  • Keep editor code to returning query arguments: no output, no writes, and logic in a named function you can test.
  • Guard every query filter on the six-character element ID, and keep the IDs in one dispatcher map so duplicates are easy to update.
  • Always return the arguments array from a filter, and change specific keys instead of replacing the whole array.
  • Never pass an empty list to post__in; return an array containing zero to match nothing.
  • Sanitise every request value (wp_unslash, type checks, sanitize_key or absint), then validate it against an allow-list or a range.
  • Never let request input change post status, post types with private content, or capability checks.
  • Test URL-driven loops through Load more, infinite scroll and AJAX pagination, since those are separate requests.
  • Add the sanitised request parameter to any cache key, and check how the page cache treats query strings.
  • Allow-list the function names used in echo tags through the bricks/code/echo_function_names filter, and keep the list short.
  • Sanitise array and API data at the source, and check what each tag outputs instead of assuming it is escaped.
  • Cache only the expensive part, store IDs not objects, give the transient a lifetime and a versioned key, and make the code work when the cache is empty.
  • Invalidate on editorial events (publish, unpublish, delete) and never write data from inside a query filter.
  • Run the test plan on staging: fixtures, cold and warm calls, empty state, invalidation, pagination with ties, and a duplicated loop.

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

Should I use the Bricks query editor or a PHP filter?

Use the controls first. When you need PHP, a filter in your child theme or a small plugin is usually safer: the code sits in a file you can review and version, it needs no code execution setting or signature, and it keeps executable code out of the database. The query editor is convenient and supports dynamic data, but it requires code execution, the execute code capability and a valid signature, and a global query using it affects every loop that references it.

What arguments does the bricks/posts/query_vars filter receive?

The Bricks documentation describes four: the associative array of arguments that will feed WP_Query, the settings array holding the loop element's builder settings, the element ID as a string, and the element name. The terms and users versions of the filter follow the same shape. Register your callback with the number of arguments you want, compare the element ID so it only affects your loop, and always return the arguments array.

How do I find the element ID of a loop?

Select the loop element in the builder and read its selector, which shows the element's ID in the form brxe followed by six characters. The Query Loop documentation describes the query ID as that six-character ID without the prefix, so a loop shown as #brxe-abc123 has the ID abc123. Duplicating an element creates a new ID, so filters keyed to the old one will not match the copy until you add the new ID.

Why does my loop show every post when my list of IDs is empty?

In WP_Query an empty post__in means no restriction, so the query returns all posts. When your logic produces no IDs and you want an empty loop, set post__in to an array containing zero, which matches no post. The Bricks documentation examples use this approach. Check other list arguments that behave the same way, such as author__in and tax_query, and test the empty state deliberately.

Is it safe to read the URL in a query loop filter?

It is safe if you treat the value as hostile. Unslash it, reject unexpected types such as arrays, sanitise it with a function such as sanitize_key or absint, then validate it against an allow-list, for example a taxonomy term that really exists. Never use request input to widen post status or visibility. Remember that pages varying by query string need a page cache that includes it, and that transient keys must include the sanitised value.

Why does my query filter not fire for every loop on the page?

Bricks runs each unique query once per page load and reuses the results, so filters tied to query execution may not run repeatedly. The documentation lists the affected filters and offers a force-run filter, plus a bricks_force_run key you can set in the query arguments, for cases that truly need a fresh run. Design hooks without side effects, because call counts are not reliable.

Can I loop over a PHP array in Bricks?

Yes. Set the loop's query type to Array and enter the array source in the Array editor. The documentation shows calling your own function with an echo tag, such as echo followed by a function name and parentheses in curly braces, provided code execution is enabled and the function name is allowed through the bricks/code/echo_function_names filter. Inside the loop, the query_array tag outputs the current item or a key of it.

Can I use Query Filters or Live Search on an array or API loop?

No. The Bricks documentation states that Query Filters and Live Search work with post, term and user query loops and do not target API or array loops. If you need faceted filtering or search over external data, consider syncing that data into WordPress as posts or terms, or building your own filtering with a custom integration, instead of expecting the interface features to apply.

What is the current loop object and how do I read it in PHP?

It is the item of the current iteration: a WP_Post, WP_Term or WP_User for native queries, or an array item for array and API loops. The documentation names the static helpers get_loop_object_id, get_loop_object_type and get_query_object_type on the Bricks Query class, and the loop_object filters. A static accessor for the whole object appears in community code but is not documented, so check your installed version or capture the object yourself in the loop_object filter.

Should I cache the whole query or only part of it?

Cache the expensive part and keep the cheap part live. Store a computed list of IDs in a transient with a lifetime and a versioned key, then let the loop fetch those posts by ID so edits to titles and images show immediately. Remember that a transient is only a cache: with a persistent object cache it lives in memory and can vanish, and without one it lives in the options table. Your code must work when it is gone.

Why is my Query editor code not running?

Check the three gates. Code execution must be enabled in the Bricks settings under Custom code, your user must hold the execute code capability, and the code must carry a valid signature. Editing signed code invalidates the signature until it is signed again, and changing the WordPress secret keys invalidates all of them. The Code review tool in the settings lists each instance with its signature status so you can see which ones are unsigned or invalid.

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