A “browse by topic” page looks simple on paper: every category as a heading, and under each heading the four newest posts in that category. In Bricks Builder that page needs two kinds of query. One query fetches the categories, and then a separate query fetches the posts for each category. The way you wire the two together is called a nested query loop: a terms loop on the outside, a posts loop on the inside, and the inner loop runs once for every result of the outer one.
The single most important idea in this tutorial is that the inner loop is not a layout trick that comes for free. It is a real database query that runs once per outer result. Everything else follows from that. The page cost is the number of categories plus one, so a list of forty categories runs forty-one queries before you have styled anything. The inner query has to be told which category it belongs to, and Bricks gives it that information through dynamic data placed in the inner loop’s own query controls. And once you are inside the inner loop, dynamic data reads the inner result, not the category around it, which is why the category name and link normally live outside the inner loop, as siblings of the posts rather than their children.
This tutorial builds the grouped list from the outside in. It starts with the shape of the nested structure and a cost model you can reason with, then builds the outer terms loop and the inner posts loop with the Bricks controls, explains exactly what dynamic data can and cannot reach in a nested loop, and shows the markup and CSS that turn the result into a clean grouped list. After that it covers the cases where you need PHP: capping the cost with Bricks filters, and the alternative of grouping the data once in PHP and looping an array instead of nesting queries. The later sections deal with accordions of categories, filtering the inner lists by search or tab (where the Bricks Query Filters have a documented limit), archive templates and the main query, the symptoms people actually report and what causes them, and a measuring routine so you know what the page costs before and after.
A few honest boundaries. This is a general guide based on the public Bricks documentation, not a hands-on test report, and it contains no benchmark numbers. The control names, dynamic data tags and hooks used here were checked against the Bricks Academy at the time of writing, but Bricks changes between versions, so where a behaviour is version-sensitive the text says so and the current Bricks documentation is the final word. Where a name could not be confirmed, the text describes what to look for in the interface instead of guessing. Example figures, such as a site with twelve categories, are illustrations to reason with, not measurements.
What you need: a site with Bricks, a taxonomy with posts in it (the built-in categories on standard posts are enough), and, for the PHP sections only, a child theme or a code snippet plugin. The main build needs no code at all. The PHP parts are safety nets and an alternative, and some of them require Bricks code execution to be switched on for your user, which is a deliberate security setting that should be enabled for as few people as possible and never for people you do not trust completely.
Key points
- A nested loop is a terms query on the outside and a posts query on the inside, so a page runs one query for the terms plus one per term: terms plus one, before any extras.
- Inside the inner loop, dynamic data reads the inner result; Bricks has no parent-loop syntax for output tags, so the term name, link and count belong outside the inner loop.
- The inner query learns its term from a dynamic data tag such as {term_id} placed in its own query controls, for example the terms field of the Taxonomy Query.
- Cap the cost on purpose: set the outer Number, set Posts Per Page on the inner loop, turn on No Found Rows, and if the page still queries too much, group the data once in PHP and loop the array.
- Bricks Query Filters target the outer supported query layer, not a deeply nested inner loop, so inner search and tabs need small client-side code or a restructured outer loop.
- On archive and search templates, switch on Disable Query Merge for loops that are not the main query, and test the page with and without a page cache.
The shape of a nested loop and the one rule behind it
A Bricks query loop works on one element. You enable Use Query Loop on a layout element (Container, Section, Block and Div offer it; the classic Accordion and Slider have their own variant), open the Query control, and choose what to query. Bricks then renders that element once per result, and everything inside it is repeated with the current result as its context. That makes the loop element the repeated item, not its parent: the element that carries the loop is the card, the row or the list item.
Nesting means placing a second loop element inside the first. For the grouped list, the outer loop element has the query Type set to Terms with the Category taxonomy, so it repeats once per category. The inner loop element has the Type set to Posts, so it repeats once per post. A clean structure uses four layers: a wrapper with no loop, the outer loop element (one per category), a plain list wrapper that does not loop, and the inner loop element (one per post). The block below shows the HTML you are aiming for, with the class names you will add yourself through the CSS classes control.
<section class="topic-index">
<section class="topic-group">
<h2><a href="/category/performance/">Performance</a></h2>
<ul class="topic-posts">
<li class="topic-item"><a href="/post-one/">First post title</a></li>
<li class="topic-item"><a href="/post-two/">Second post title</a></li>
</ul>
</section>
</section>
Read it from the outside in. The element with the class topic-group is the outer loop element, so Bricks prints it once per category. The heading and its link sit directly inside it, which means they read the category. The ul has no loop, so it renders once per category and simply holds the list items. The li with the class topic-item is the inner loop element, so it renders once per post. In the builder you reach this with Div elements whose HTML tag control is set to section, ul and li; the Div’s tag list includes those and several other semantic tags. A Div suits the list parts better than a Block, because the Bricks documentation points out that a Block uses display flex by default, which can remove list markers, while a Div has no default layout styles.
The rule behind everything that follows is simple: the inner loop is a second, separate query, built fresh for each outer result. Bricks builds the inner query while the outer result is current, which is what lets a tag such as the term ID reach the inner query settings. After the query is built and run, the elements inside the inner loop only know about posts. The flow below shows one full render of one category, and the same five steps repeat for the next category.
How one nested render unfolds
- Outer query runsBricks queries the terms once. This is the one query that does not repeat.
- A term becomes currentTags such as the term name, term URL and term ID read this term while it is the current result.
- Inner query is builtThe inner loop controls, such as the Taxonomy Query terms field, resolve the term ID tag against the current term.
- Inner query runsOne posts query for this term only, with the per-page limit you set on the inner loop.
- Inner items renderEach post is now the current result, so post tags read the post, not the term.
- Next termThe cycle repeats from the second step until the terms run out.
The cost model: terms plus one, and what multiplies it
Before building anything, learn the cost rule, because it decides every later choice. The outer terms loop is one query. The inner posts loop is one query for each term. With T terms on the page the base count is T plus one. A magazine with twelve categories runs thirteen queries for the grouped list; a directory with forty categories runs forty-one. That is the number to carry into every decision, and it is also the number you can check afterwards.
The base count understates the real work, because a single post query in WordPress does more than one thing. Unless it is told otherwise, it counts the total number of matching rows so that pagination can work, and it loads the meta and term data for the posts it returns into the cache so later lookups are fast. The Bricks Posts query exposes switches for exactly these behaviours: No Found Rows for when the loop does not need pagination or result counts, and Disable update_post_meta_cache and Disable update_post_term_cache for loops that do not use that data. A grouped list never paginates the inner loops, so No Found Rows is almost always correct there. Be more careful with the cache switches: if the list items print the post’s categories or a custom field, turning the cache off makes each item look the data up separately, which is slower, not faster.
Four things multiply the cost. The first is the number of outer results, which is why the outer Number setting matters. The second is the weight of each inner query: a plain taxonomy query on recent posts is cheap, while a meta query, a sort by a custom field or a relevance search is much heavier, and you pay that weight once per term. The third is what happens inside the inner item. A featured image tag, a custom field and a post terms tag each read data per post, and if the cache was disabled they each become a query. The fourth is the number of nesting levels: a third level multiplies the second.
It helps to separate where the cost lands. A full-page cache means most visitors never trigger the queries; they receive stored HTML. The queries still run for the first request after a cache purge, for logged-in users who bypass the cache, in the builder, and on any page the cache excludes. So a heavy nested loop on a high-traffic page with a healthy cache can look fine in production and still feel slow every time you edit it, and still hurt right after every deployment. The goal is not to avoid nesting at all; it is to know the count, cap each part on purpose and keep the loop small, which is the same advice the Bricks documentation gives for nested loops in its performance guidance.
The scale below is an editorial ranking of configurations from light to heavy, not a measurement. It is there to show which settings move a nested loop toward the heavy end.
What makes a nested loop heavier
How to read this: each row is one option, and its dot shows where it sits between Light and Heavy. Placement is an editorial judgement, not a measurement.
- 1Top-level terms only, 3 posts each, No Found Rows onFew outer results and a plain inner query.
- 2All terms of a mid-sized taxonomy, 4 posts eachTerms plus one grows with the taxonomy.
- 3Inner loop prints custom fields and images per postPer-item lookups add up if caches are off.
- 4Inner query sorted or filtered by a meta valueThe heaviest part runs once per term.
- 5A third nesting level on top of thatMultiplies the whole second level.
Building the outer loop: the terms query
Start with the outer loop and get it right on its own before you add anything inside it. Add a Section or Container as the wrapper, then add a Div inside it that will be the repeated category item. Select the Div, enable Use Query Loop, open the Query control and set the Type to Terms. Give the Div a descriptive element name such as “Category group”; the Bricks documentation recommends this because the query IDs you use later are easier to recognise when elements are named.
Bricks runs a Terms query through WP_Term_Query, and its controls adapt to that. The ones you will use for a grouped list are these. Taxonomies chooses which taxonomy to loop (the default is none, so pick Category or your custom taxonomy). Order by offers term ID, name, parent, count and include list, and Order sets the direction. Number is the count of terms to show, and it deserves a careful read: WordPress itself defaults to all terms, but Bricks defaults to the number in Settings, Reading, “Blog pages show at most”, and 0 means show all. So a site that shows ten posts per page will silently list only ten categories, and the eleventh will look as if it vanished. Set Number deliberately, to a real cap rather than 0 on a taxonomy that can grow.
Show empty controls whether terms with no posts appear. For a “browse by topic” page you almost always want empty terms hidden, because a heading with nothing under it looks broken. Terms Include and Exclude lets you drop the default “Uncategorized” category or feature a hand-picked list in a specific order (Order by include list keeps your order). For hierarchical taxonomies, the Parent, Child of and Childless controls decide whether you list top-level terms, the children of one term, or only terms without children. Their exact behaviour follows WP_Term_Query, so after setting them, confirm in the canvas which terms come back instead of assuming.
Add a No Results message in the Query control for the case where the taxonomy is empty, and turn on Disable Query Merge if this page is an archive or search template, a point covered in its own section later. Then check the outer loop in isolation: put a Heading inside the Div, set its content to the term name tag, and look at the canvas and at the front end. The term name tag prints the current term’s name. You should see one heading per category, in the order you chose, with exactly the terms you expect. If this layer is wrong, nothing you build inside it can be right.
Two more tags are worth adding now because they belong to the outer layer. The term URL tag returns the archive link for the term, which you will use on a “View all” link, and the term count tag returns the number of posts assigned to the term, which is useful for a small badge. The term ID tag is the one that matters for the next section, since it is what you will hand to the inner query.
Building the inner loop: posts for the current term
With the outer loop proven, build the inside of one category. Select the outer Div and add three things in order: a Heading for the category, a Div whose HTML tag is ul, and inside that ul another Div whose HTML tag is li. The heading shows the term name tag, and you can link it to the category archive by giving it a link of the dynamic data type and choosing the term archive URL tag. The ul does not loop. The li is the inner loop element.
Select the li, enable Use Query Loop, open the Query control and keep the Type on Posts. Work through the settings in this order. Post type: Posts, or whichever post type the taxonomy is attached to. Posts Per Page: the cap per category, for example 4, because the number you set here is applied to each term separately. Order by and Order: published date, descending, for “latest”. Ignore Sticky Posts: on, otherwise sticky posts can jump to the front of every category’s list. No Found Rows: on, since the inner lists are never paginated.
Now the step that makes it a nested loop: the Taxonomy Query. Add one taxonomy query, set the taxonomy to the same one the outer loop uses, and in the terms field insert the term ID tag from the dynamic data picker (type an opening brace in the field or use the bolt icon to open the picker). The Bricks documentation states that inner query controls can use dynamic data while Bricks builds the nested query, and that is exactly what this field does: at the moment the inner query is built for a given category, the tag resolves to that category’s ID, so the posts query is restricted to that category. A community example of the same pattern, with a terms loop around a posts loop and the term ID in the taxonomy query, appears in a Bricks forum thread where the question was how to add a second grouping level.
One version note. Early reports on the Bricks forum described the terms field of the Taxonomy Query ignoring dynamic values while accepting typed ones, and the Bricks team fixed it in a later release. If the tag appears to be ignored on an old install, update Bricks and check the changelog before debugging further.
Finally, put the post content inside the li. A Basic Text element with the post title tag and the link filter renders the title as a link to the post; the Bricks documentation lists that filter on the post title tag, and it also lets you shorten the title to a number of words. If you want the date or an excerpt, add them as further elements inside the li. Everything in the li is repeated for each post, and each tag reads that post.
What happens when the inner query’s constraint is missing or empty? The posts query falls back to the unconstrained version, so every category shows the same latest posts. That identical-lists symptom is the single clearest sign that the term tag did not reach the inner query, and it is the first thing to check when a nested loop misbehaves. A second point to know: for hierarchical taxonomies, WP_Query includes the children of a term by default when it matches a term, so a parent category’s list can include posts from its sub-categories. That is often what you want for “latest in this topic”, and it is a common cause of apparent duplicates when you list parents and children together. Confirm the behaviour in your own canvas instead of assuming it.
The figure puts the two outcomes side by side. It is a plain HTML and CSS render with example post titles, drawn from the same kind of list markup as the rest of this guide, not a screenshot of the Bricks editor. On the left, the same three posts sit under every heading. On the right, each heading has its own posts.

Dynamic data in nested loops: what you can and cannot reach
The rule in the Bricks documentation is short and worth memorising. Dynamic data uses the current loop result, and in a nested loop the inner result becomes the current result for the elements inside the inner loop. The documentation’s own example uses the term name tag: it returns the current term in an outer Terms loop, but inside a nested Posts loop the current result is a post, so the same term tag does not read the outer term. Bricks does not provide a parent-loop syntax for output tags. Inner query controls can use dynamic data while Bricks builds the nested query, but anything printed inside the inner loop resolves against the inner result.
That produces a clear design rule: put everything that belongs to the category outside the inner loop element and inside the outer loop element. The heading, the archive link, the post count and a “View all” link are siblings of the ul, not children of the li. In the structure from the first section that is where they already sit, which is why the list is a good shape for nesting: the term-owned content and the post-owned content live at different depths and never need to see each other.
Sometimes you do want the category inside each item, for example a small label on every list item. You have four honest options. Restructure so the label is not needed. Use the post’s own terms tag, which prints the terms assigned to that post; it can list several terms and is not tied to the outer category, so it only matches the outer term when posts have a single category. Group the data in PHP so the category name is copied into every item, which is what the array approach later in this tutorial does. Or write a custom dynamic data tag in PHP; the Bricks developer documentation covers creating your own dynamic data tag, and the Academy states plainly that reaching the parent result from inner-loop markup needs custom PHP or a custom tag.
A few related tags behave the way you would hope. The loop index tag returns the index of the current loop item starting at 0, and takes an argument to start at another number, so a ranking such as “1, 2, 3” on the outer loop is an index with a start of 1; it counts within whichever loop the element sits in, so the inner loop restarts at the beginning for each category. The results count tag returns the number of results for a query and, when used outside the loop, needs the loop’s query ID passed to it, which is the six-character Bricks ID of the loop element. Element conditions are evaluated with the current loop object, so an element inside the outer loop can compare the term count tag against a number and render only for large categories, which is the right way to show a “View all” link only when more posts exist than the inner loop displays. The second figure below shows that result as a plain HTML and CSS render with example numbers, not a screenshot of the Bricks editor: categories ordered by post count, a rank number from the index tag with a start of 1, and a View all link on the two categories that have more posts than the four the inner loop shows.
Keep one more limit in mind. Everything above is about dynamic data in output. The controls of a loop can use dynamic data in a different way: they are resolved while the query is built, which is why the term ID tag works in the inner Taxonomy Query. The two moments are different, and confusing them is the cause of most “my tag works here but not there” questions in nested loops. The stack below shows what each layer reads.
What each layer of a nested loop reads

The grouped list rendered: markup, CSS and accessibility
With the structure and the queries in place, the rest is presentation. The CSS below styles the classes from the first section as a responsive grid of category cards. Add the classes to the elements through the CSS classes control, and put the CSS somewhere that matches its scope: the page’s custom code (Page Settings, Custom Code) if it belongs to this page or template, or a global class if the pattern repeats. Element-level custom CSS also works; the Bricks documentation says the %root% placeholder in element CSS is converted to the element’s own selector, so you can write rules for that element without knowing its ID.
.topic-index {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
gap: 1.5rem;
}
.topic-group {
padding: 1.25rem;
border: 1px solid #d5dbe5;
border-radius: 0.75rem;
background: #ffffff;
}
.topic-group h2 {
margin: 0 0 0.75rem;
font-size: 1.25rem;
line-height: 1.3;
}
.topic-posts {
margin: 0;
padding: 0;
list-style: none;
}
.topic-item + .topic-item {
border-top: 1px solid #e9edf3;
}
.topic-item a {
display: block;
padding: 0.5rem 0;
text-decoration: none;
}
.topic-item a:hover,
.topic-item a:focus-visible {
text-decoration: underline;
}
.topic-more {
display: inline-block;
margin-top: 0.75rem;
font-weight: 600;
}
What the important lines do. The grid on the wrapper uses auto-fit with a minimum column width wrapped in min(), so cards flow from several columns down to one without a media query and never overflow a narrow phone. The border and padding on the group make each category a visible unit. Removing list styles from the ul keeps the clean look, and the sibling selector draws a divider between items without adding a border to the first one. The link is displayed as a block so the whole row is a comfortable tap target, and the focus-visible rule gives keyboard users a clear marker without showing it on mouse clicks. The topic-more class is for the “View all” link.
Three accessibility points are worth the minute they cost. Keep the heading level consistent with the page: if the page title is an h1, the category headings are h2, and the Heading element lets you choose the tag. Write the “View all” link so it names its target, for example “View all 12 posts in Performance” built from the term count and term name tags, because a row of identical “View all” links is useless to someone navigating by links. And note that on some browser and screen reader combinations a list loses its list semantics when list-style is none; if that matters for your audience, add a role of list to the ul through the element’s custom attributes.
The figure is a plain HTML and CSS render of this technique, drawn in a browser from the same markup and a trimmed version of this CSS. It is not a screenshot of the Bricks editor.

When you need PHP: the Query editor and two safety-net filters
The no-code build is enough for most grouped lists. Reach for PHP in two situations: when the inner query needs logic the controls cannot express, and when you want a cap that an editor cannot accidentally remove. Bricks gives you two routes. The Query editor replaces the controls with code, and the query filters adjust the arguments Bricks has already assembled.
The Query editor appears when you enable the Query editor (PHP) control in the loop’s Query settings. It is a security-sensitive feature, so three conditions apply, all stated in the Bricks documentation: code execution must be enabled in the Bricks settings, your user must be allowed to execute code, and the saved code must carry a valid signature. If the signature is missing or invalid, for example after the WordPress secret keys change, Bricks will not run the code at all. The code must return a PHP array of WordPress query arguments, and the documentation says the editor supports dynamic data. This is the inner loop rewritten as code. The tag is written inside quotes and cast to an integer, so an unresolved tag still produces valid PHP.
$term_id = (int) '{term_id}';
if ( $term_id < 1 ) {
// Return nothing rather than everything when the tag did not resolve.
return [ 'post__in' => [ 0 ] ];
}
return [
'post_type' => 'post',
'posts_per_page' => 4,
'ignore_sticky_posts' => true,
'no_found_rows' => true,
'tax_query' => [
[
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => [ $term_id ],
],
],
];
Line by line. The first line asks Bricks to substitute the current term’s ID and forces an integer. The guard returns a post__in list containing only zero, which matches no post, so a failed substitution shows an empty list instead of the same latest posts under every heading; that failure is far easier to notice and diagnose. The returned array is ordinary WP_Query arguments: the per-category limit, sticky posts ignored, found rows skipped, and a taxonomy query on the term ID. Keep the editor focused on this. The Bricks documentation warns against echoing output or running unrelated database writes inside a Query editor, and the code runs on every render.
The second route is a pair of guard rails that live in your theme, not in the page. The filters below receive the query arguments after Bricks has built them. The signature is the one in the Bricks documentation, and the extra arguments are given defaults so the callback cannot raise an error on a version that passes fewer of them. Replace the six-character IDs with the IDs of your own loop elements, which you can read from the element’s ID or from the copy option in the context menu.
add_filter( 'bricks/posts/query_vars', function ( $query_vars, $settings = [], $element_id = '', $element_name = '' ) {
// ID of the INNER posts loop element.
if ( 'abc123' !== $element_id ) {
return $query_vars;
}
$per_page = isset( $query_vars['posts_per_page'] ) ? (int) $query_vars['posts_per_page'] : 4;
$query_vars['posts_per_page'] = max( 1, min( $per_page, 6 ) );
$query_vars['no_found_rows'] = true;
$query_vars['ignore_sticky_posts'] = true;
return $query_vars;
}, 10, 4 );
add_filter( 'bricks/terms/query_vars', function ( $query_vars, $settings = [], $element_id = '', $element_name = '' ) {
// ID of the OUTER terms loop element.
if ( 'xyz789' !== $element_id ) {
return $query_vars;
}
$number = isset( $query_vars['number'] ) ? (int) $query_vars['number'] : 0;
// Never allow "all terms" (0) or a huge number on this loop.
$query_vars['number'] = ( $number < 1 || $number > 30 ) ? 30 : $number;
return $query_vars;
}, 10, 4 );
The first filter clamps the inner per-page value between one and six, so an editor who types 50 gets 6, and it forces No Found Rows and ignores sticky posts. The second makes sure the outer loop can never mean “every term” on a taxonomy that may grow. Put both in a child theme’s functions file or a small site plugin, not in the parent theme, so updates do not remove them. One caveat: the guard is tied to the element ID, so if someone rebuilds the loop element instead of editing it, the ID changes and the cap quietly stops applying. Re-check the IDs after any restructuring.
Skipping the nesting: group in PHP once, loop the array
Terms plus one is the price of nesting queries. If all you need is the newest few posts per category, there is a cheaper shape: run one posts query for recent posts, group them by category in PHP, store the result for a while, and let Bricks loop the grouped array with the Array query type. The Bricks documentation describes that type as looping through any PHP or JSON array, and shows the two pieces you need: the echo dynamic tag, which can call a PHP function that returns an array, and the nested array loop, where the inner loop’s Array Editor reads a key of the current item.
Two safety requirements come with it. The echo tag only calls functions you have explicitly allowed through the bricks/code/echo_function_names filter, and code execution must be enabled for the users involved, as described in the Bricks documentation. The function below builds the groups from one query, relies on the term cache that the query primes, and keeps the result in a transient that is cleared whenever content or terms change.
function wpp_topic_groups() {
$cached = get_transient( 'wpp_topic_groups' );
if ( is_array( $cached ) ) {
return $cached;
}
$posts = get_posts( [
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 120,
'no_found_rows' => true,
'ignore_sticky_posts' => true,
] );
$groups = [];
foreach ( $posts as $post ) {
foreach ( get_the_category( $post->ID ) as $term ) {
if ( ! isset( $groups[ $term->term_id ] ) ) {
$link = get_term_link( $term );
$groups[ $term->term_id ] = [
'name' => esc_html( $term->name ),
'url' => is_wp_error( $link ) ? '' : esc_url( $link ),
'count' => (int) $term->count,
'posts' => [],
];
}
if ( count( $groups[ $term->term_id ]['posts'] ) < 4 ) {
$groups[ $term->term_id ]['posts'][] = [
'title' => esc_html( get_the_title( $post ) ),
'url' => esc_url( get_permalink( $post ) ),
];
}
}
}
$groups = array_values( $groups );
set_transient( 'wpp_topic_groups', $groups, 6 * HOUR_IN_SECONDS );
return $groups;
}
function wpp_topic_groups_flush() {
delete_transient( 'wpp_topic_groups' );
}
foreach ( [ 'save_post', 'deleted_post', 'edited_term', 'created_term', 'delete_term' ] as $wpp_hook ) {
add_action( $wpp_hook, 'wpp_topic_groups_flush' );
}
add_filter( 'bricks/code/echo_function_names', function () {
return [ 'wpp_topic_groups' ];
} );
What each part does. The query fetches the newest 120 published posts once, without counting rows. For each post, get_the_category reads the categories from the cache that the query already primed, so it adds no query per post. The loop builds one group per category and keeps at most four posts in each. Names and titles are escaped as they are stored and URLs go through esc_url. The transient keeps the finished array for six hours, and the flush function deletes it on post saves, post deletes and term changes, so editors do not wait for the timeout. The last filter is the allow-list that the echo tag requires.
In the builder, the outer Div gets Use Query Loop with the Type set to Array, and the Array Editor holds the call with its parentheses: {echo:wpp_topic_groups()}. Inside it, the heading text is {query_array @key:'name'} and its link is {query_array @key:'url'}. The ul stays a plain wrapper. The li gets its own Use Query Loop, Type Array, and an Array Editor value of {query_array @key:'posts'}, which is the pattern the Bricks documentation shows for looping a nested array. Inside the li, {query_array @key:'title'} is the text and {query_array @key:'url'} the link. The documentation’s nested example loops a list of plain strings; with items that are themselves arrays, as here, confirm in the canvas that the key tags resolve before you style anything.
Know the trade-offs before choosing it. The per-category limit is approximate: categories whose newest posts fall outside the 120-post window will be short or missing, which matters on sites with very uneven categories. Query Filters do not support array loops according to the Bricks documentation, so filter elements cannot target this list. The function is code you maintain, the echo allow-list must be kept in step with your function names, and a cache you have to invalidate is a cache you can get wrong. In return the page runs one posts query on a cache miss and none on a hit, and every inner item can carry whatever the PHP copied into it, including the category name, which nested Bricks loops cannot give you.
Nested Bricks loops or a grouped array
| Nested Bricks loops | Grouped in PHP, Array loop | |
|---|---|---|
| Queries per uncached render | Terms plus one | One posts query, none when cached |
| Per-category limit | Exact, set on the inner loop | Approximate, depends on the window |
| Parent value in each item | Not reachable with output tags | Copied into the array by your code |
| Query Filters | Outer terms loop only | Not supported for array loops |
| Setup | Builder controls, no code | PHP function and code execution |
| Cache invalidation | Page cache only | Your transient plus the page cache |
Accordions of categories without breaking the loop
A grouped list becomes a compact accordion when each category is a collapsible panel. The tempting route is the Accordion elements, and it is worth knowing why it does not fit this job. The Bricks documentation says the classic Accordion element can take a query loop, creating one item per result with the title, subtitle and content of the first item acting as the template; those parts are fields, not a free layout, so a panel’s content cannot hold an inner posts loop. It also says the nestable elements, Accordion (nestable), Tabs (nestable) and Slider (nestable), use their own child repeaters and do not expose the full Query Loop control that layout elements have. For a category with a list of posts inside it, the dependable structure is the browser’s own details and summary elements, built from Div elements.
Select the outer loop Div and set its HTML tag to custom, then type details as the custom tag. Inside it, add a Div with the custom tag summary, containing the term name (and the count if you like), and put the ul after it, unchanged. Bricks checks custom tag names against an allowed list. If details or summary is rejected, the bricks/allowed_html_tags filter documented for exactly this purpose adds them.
add_filter( 'bricks/allowed_html_tags', function ( $allowed_html_tags ) {
$allowed_html_tags[] = 'details';
$allowed_html_tags[] = 'summary';
return $allowed_html_tags;
} );
That adds the two tag names to the list Bricks accepts. Then style the panel. The CSS below draws the border, hides the default marker, adds a plus or minus indicator from CSS and keeps a visible keyboard focus ring.
.topic-acc {
border: 1px solid #d5dbe5;
border-radius: 0.75rem;
}
.topic-acc + .topic-acc {
margin-top: 0.75rem;
}
.topic-acc summary {
display: flex;
justify-content: space-between;
gap: 1rem;
padding: 1rem 1.25rem;
font-weight: 600;
cursor: pointer;
list-style: none;
}
.topic-acc summary::-webkit-details-marker {
display: none;
}
.topic-acc summary::after {
content: "+";
font-weight: 400;
}
.topic-acc[open=""] summary::after {
content: "\2212";
}
.topic-acc summary:focus-visible {
outline: 2px solid currentColor;
outline-offset: 2px;
}
.topic-acc .topic-posts {
padding: 0 1.25rem 1rem;
}
Why this is a good fit. The summary is a native control: it is focusable, it toggles with Enter and Space, and it announces its expanded state to assistive technology, all with no JavaScript. Closed panels are still in the page source, so nothing is hidden from search crawlers or from the browser’s find-in-page in browsers that expand matches. You add the class to the outer Div through the CSS classes control. The open-state selector is written as an attribute match against an empty value, which is how the browser stores the boolean open attribute once a panel is expanded.
One cost point that surprises people: collapsing a panel hides the output but does not remove the query. Every inner posts query still runs on the server for the whole page, open or closed, so an accordion of forty categories is exactly as expensive as a list of forty categories. If that is too much, the levers are the ones from the cost section: fewer outer terms, a smaller inner limit, or a grouped array. Loading each panel’s posts on demand with a request is possible, but that is custom JavaScript and a custom endpoint, and it is outside what the Bricks controls provide.

Filtering the inner lists: search, tabs and a documented limit
Visitors often want to narrow a long grouped list: search for a word, or show one category at a time. Start with what Bricks documents. The Query Filters system, which adds filter elements, URL parameters and AJAX updates to a loop, supports post, term and user loops, and each filter element has a Target query that points at a loop by its element ID. The same page also lists what it does not support: API loops, array loops, and deeply nested query targets. In nested scenarios, filters target the outer supported query layer, and you should not expect a filter outside the loop to reach a deeply nested child query. So a Filter element can narrow which categories the outer terms loop lists, but it is not the tool for filtering the posts inside every category.
For the inner posts, the most reliable option is a small piece of client-side code that hides list items that do not match what the visitor typed. It needs no query, no request and no dependency, and it works because the items are already in the page. Add a search input with an HTML element (a label, an input of type search and an empty paragraph that will announce the result count), give the groups and items the classes from earlier, and add the script to the page’s custom JavaScript (Page Settings, Custom Code); check whether the field you use expects script tags, since the Bricks documentation says the global script fields do.
<label for="topic-search">Filter the posts on this page</label>
<input id="topic-search" class="topic-search" type="search" autocomplete="off">
<p class="topic-status" aria-live="polite"></p>
(function () {
var input = document.querySelector('.topic-search');
var status = document.querySelector('.topic-status');
var groups = document.querySelectorAll('.topic-group');
if (!input || !groups.length) { return; }
var timer = null;
function normalise(text) {
return text.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '');
}
function apply() {
var query = normalise(input.value.trim());
var total = 0;
groups.forEach(function (group) {
var visible = 0;
group.querySelectorAll('.topic-item').forEach(function (item) {
var match = query === '' || normalise(item.textContent).indexOf(query) !== -1;
item.classList.toggle('is-filtered-out', !match);
if (match) { visible += 1; }
});
group.classList.toggle('is-filtered-out', visible === 0);
total += visible;
});
if (status) {
status.textContent = query === '' ? '' : total + (total === 1 ? ' post matches' : ' posts match');
}
}
input.addEventListener('input', function () {
window.clearTimeout(timer);
timer = window.setTimeout(apply, 150);
});
})();
.is-filtered-out {
display: none !important;
}
.topic-search {
width: 100%;
max-width: 28rem;
padding: 0.6rem 0.8rem;
border: 1px solid #b8c1d1;
border-radius: 0.5rem;
font: inherit;
}
.topic-status {
min-height: 1.5em;
margin: 0.5rem 0 0;
font-size: 0.9rem;
}
How it works. The function normalises text by lowercasing it and stripping accents, so a search for “cafe” also finds “café”. Each time the visitor types, a short timer waits 150 milliseconds so the work runs once per pause, not once per key. For every group it checks each item’s text, toggles a class on non-matching items, and hides the whole group when none of its items match, so empty headings do not linger. The paragraph with aria-live set to polite receives the count text, which screen reader users hear without losing focus. A class is used instead of the hidden attribute on purpose: any display rule on the element, such as a flex layout from a Bricks Block, outranks the attribute, so hidden items would stay visible. The !important in the class closes that gap.
Be clear about the limit: this searches only the titles on the page, which means the four or so posts shown per category, not every post on the site. For a site-wide search, keep it out of the nested structure. Use a separate posts loop with a Filter – Search element and Live Search, which the Bricks documentation supports for post loops. The decision below summarises which tool fits which question. For “one category at a time”, the cleanest answer is usually a link to each term archive, which gives every category its own crawlable URL; a filter on the outer terms loop is the alternative when you want it on one page. Check which filter elements and sources the builder offers for a terms loop in your version, because the documentation lists terms as supported without listing every combination.
The second figure shows the search state this script produces after a visitor types the word cache. It is a plain HTML and CSS render of the technique, with the same hiding class as the stylesheet above, not a screenshot of the Bricks editor. Three titles contain the word, so the status line reports three matches, the matching items stay, and the Security group disappears because none of its items match.
Which tool narrows which list

Archive templates, the main query and pagination
Nested loops on a normal page behave as described so far. On an archive or search template there is an extra layer, because Bricks can merge a loop’s query with the query WordPress already ran for that URL. The Bricks documentation explains the control: Disable Query Merge turns off the automatic merge in archive pages, search pages and similar, and you normally turn it on for loops that are not the main query, such as loops in a header, a footer or an extra section. Posts, Terms and Users queries each have it. A nested list placed on a category archive template without it can inherit the archive’s constraints, and the symptom is a list that is mysteriously limited to the current category or paginated by the archive’s page number.
The related control is Is main query, available on Posts loops in archive and search templates. It marks one loop as the template’s main query so pagination across archive pages does not return a 404. The documentation is explicit that only one loop on a page should be the main query, because only the first one is honoured, and that the Pagination element must be pointed at that loop. A grouped list is rarely the main query. Its outer loop lists terms, and the inner loops are small windows, so on an archive template give every loop in the nested structure Disable Query Merge and leave the main query to the loop that actually lists the archive’s posts.
Pagination for a nested structure needs a plain decision. The Pagination element attaches to one loop through its Related Query control, and it has an Enable AJAX setting for updating that loop without a full reload, which is how it cooperates with Query Filters. Point it at the outer loop if the terms themselves are paged, for example thirty categories, ten per page, using the Number setting. Do not try to paginate the inner lists; they are deliberately short windows, and the way to reach the rest is the “View all” link to the term archive, which has real pagination of its own and a URL search engines can crawl.
Two infrastructure notes close the section. Bricks writes HTML comments such as brx-loop-start with the loop’s ID into the output, and the documentation says features like AJAX pagination, filters, Load More and infinite scroll depend on them; some optimisation plugins strip all HTML comments by default, which breaks those features, so exclude Bricks’ comments if you use one. And for hierarchical taxonomies, recent Bricks releases list term parent and term children tags among the term tags, which return the parent’s name and the direct children’s names, useful for a “Sub-topics” line under a parent heading; the documentation marks them as newer additions, so confirm they exist in your version before relying on them.
What goes wrong: symptoms, causes and fixes
Nested loops fail in a small number of recognisable ways. Work from the symptom to the cause, and check the outer loop on its own before you suspect the inner one.
- Every category shows the same posts. The inner query is not being constrained by the current term. Check that the Taxonomy Query has a taxonomy and the term ID tag in its terms field, that the inner loop element is actually inside the outer loop element, and that you are not on an old release that ignored dynamic values in that field. With the Query editor, confirm code execution is enabled and the code is signed, because Bricks does not run unsigned code.
- A heading appears with nothing under it. The inner Post type does not match the content that carries the term, the inner taxonomy is a different one from the outer taxonomy (tags instead of categories, for example), or the term is shown because Show empty is on while its posts are drafts or another post type.
- A category is missing. The outer Number follows the Reading setting by default, so a limit of ten silently hides the eleventh term. Also check Show empty, Terms Include and Exclude, and the Parent, Child of and Childless controls.
- The same post appears under a parent and its child. A taxonomy query on a hierarchical term includes child terms by default, so a post in a sub-category also belongs to its parent’s list. List only top-level terms, exclude the children, or accept the repeat on purpose.
- The category name is blank or wrong inside a list item. Term tags inside the inner loop do not read the outer term. Move the content outside the inner loop, or use one of the options from the dynamic data section.
- The list is fast for visitors and slow for you. A page cache hides the queries from visitors. Logged-in users, the builder and the first request after a purge pay the full cost. Measure with the cache bypassed.
- A PHP cap does nothing. The element ID in the filter no longer matches because the loop element was rebuilt, the code is in the wrong file, or a function called from the echo tag is not on the allow-list.
- The canvas and the front end disagree. The Bricks documentation describes a maximum results limit applied to queries inside the builder, and dynamic data text on the canvas is controlled by a builder setting. Judge the result on the front end.
- AJAX features stop working on the outer loop. An optimisation plugin may have stripped the Bricks loop comments, which the documentation lists as required markers.
The decision below condenses the first four into a starting point. The habit that saves the most time is to change one thing, reload the front end and compare, because with two query layers it is easy to fix a symptom in the wrong layer.
Reading a nested loop symptom
Measuring the cost and keeping it down
The cost model says what to expect; measuring tells you whether you got it. The number to watch is not a stopwatch time on your own machine but the number of database queries WordPress runs for an uncached request, plus the slowest single query. WordPress can tell you the first directly. The snippet below prints the query count as an HTML comment at the end of the page, only for administrators. View the page source, find the comment, and compare counts as you build. Remove it when you are done.
add_action( 'wp_footer', function () {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
printf( "\n<!-- database queries: %d -->\n", get_num_queries() );
}, 999 );
The callback runs near the end of the page, checks that the visitor is an administrator and prints the count that WordPress keeps for the request. Because administrators are logged in, most page caches serve them uncached HTML, so the number reflects the real work. Add the snippet to a child theme or a small plugin. For the detail behind the number, a query profiler plugin lists every query with the function that triggered it, which is how you spot repeated lookups and see which part of a nested loop is heaviest; the WPresident guide on that kind of tool covers the workflow.
Then measure in steps, as the timeline shows. First record the count of the page with no loops. Add the outer loop alone and recount. Add the inner loop and expect the count to rise by about one per term, plus the extra work around each query if the cache switches are left on. Apply the caps and recount. If the count is still too high for the page’s traffic, move to the grouped array or reduce the number of terms. Finally, test the page with and without the page cache and after a purge, since those are three different costs.
Caching deserves a plain ranking. The page cache is the biggest lever for visitors, and it needs to be purged when posts or terms change, which most cache plugins do on publish. A persistent object cache can answer repeated lookups from memory rather than the database across requests, but it does not replace capping the loop. A transient, as in the grouped array, caches your own computed result and is yours to invalidate. If your site is multilingual, remember that cached results can mix languages unless the cache key includes the language; the Bricks documentation describes the bricks/query/cache_key filter for adding context such as language to the key of a loop’s cached query.
Finally, build a habit of looking at the structure before the styling. A nested loop that is wrong in the structure cannot be rescued by CSS, and one that is right but unbounded will eventually surprise you when a taxonomy grows. Cap the outer count, cap the inner count, switch off what the list does not use, count the queries, and write down the numbers you accepted so the next person knows what changed.
A measuring routine for a nested loop
Checklist
- Decide the data shape first: which taxonomy, how many terms now and in a year, and how many posts per term you will show.
- Build and verify the outer terms loop on its own before adding anything inside it.
- Set the outer Number on purpose: it follows the Reading setting by default and 0 means all terms.
- Hide empty terms and exclude the default Uncategorized category or any other terms you do not want listed.
- Give both loop elements descriptive names so their query IDs are easy to recognise later.
- Put the term ID tag in the terms field of the inner Taxonomy Query and confirm on the front end that each section shows different posts.
- Set Posts Per Page, Ignore Sticky Posts and No Found Rows on the inner loop.
- Keep term-owned content (heading, archive link, count, View all) outside the inner loop element.
- Use Div elements with the ul and li tags for the list, check that list markers behave, and add a list role if you need it.
- Write link text that names its target and keep the heading levels consistent with the page.
- On archive and search templates, turn on Disable Query Merge for every loop in the structure that is not the main query.
- If you use the Query editor, enable code execution only for trusted users, return query arguments only and re-sign after edits.
- Add PHP caps with the posts and terms query vars filters if editors can change the loops, and re-check the element IDs after any rebuild.
- Consider a grouped array with a transient when the term count is high, and flush it on post and term changes.
- Do not count on collapsed accordion panels to save queries; every inner query still runs.
- Count the database queries before and after adding the loops, logged in and logged out.
- Test with the page cache off, on and after a purge, and confirm any optimisation plugin keeps the Bricks loop comments.
- Re-check the page after Bricks updates, because controls and behaviours can change between versions.
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
Can I nest a posts loop inside a terms loop in Bricks without writing code?
Yes. Enable the query loop on a Div and set the Type to Terms, then place a second Div inside it with the query loop set to Posts and put the term ID dynamic data tag in the terms field of its Taxonomy Query. The Bricks documentation says inner query controls can use dynamic data while the nested query is built. Code is only needed for logic the controls cannot express or to enforce caps. Always confirm on the front end that each section shows different posts.
How many levels of nesting are sensible?
Two is the practical limit for most sites. Each extra level multiplies the queries of the level above it, the Bricks documentation advises keeping nested loops small, and Query Filters do not support deeply nested targets. If you think you need three levels, flatten the data in PHP and loop an array, or split the page so each level has its own URL, for example a term archive for each category.
Why does every category show the same posts?
The inner query is not being constrained by the current term. Check that the Taxonomy Query has a taxonomy and the term ID tag in its terms field, that the inner loop element sits inside the outer loop element, and that you are not on an old release that ignored dynamic values in that field. With the Query editor, check that code execution is enabled and the code is signed, because unsigned code is not run.
Can the inner loop print the category name?
Not with an output tag. Bricks has no parent-loop syntax, so dynamic data inside the inner loop reads the inner result, the post. Put the category name outside the inner loop element, use the post's own terms tag if each post has one category, copy the name into array data in PHP, or write a custom dynamic data tag. The Bricks documentation says reaching the parent result from inner markup needs custom PHP or a custom tag.
How do I limit the number of posts per category?
Set Posts Per Page on the inner loop. The inner query runs separately for each term, so the limit applies to each category. To stop editors raising it, clamp the value with the bricks/posts/query_vars filter for that element's ID. With the grouped array method the limit is the count in your PHP loop, with the caveat that it only sees posts inside the window you queried.
Does closing an accordion panel reduce the number of queries?
No. Collapsing is a visual state. The server still runs every inner query to build the page, open or closed, so an accordion of forty categories costs the same as a list of forty. To reduce the cost, list fewer terms, lower the inner limit, switch off unused cache and count options, or group the data once in PHP and cache it.
Can I paginate the inner lists?
Not in a useful way. The Pagination element attaches to one loop, and the inner lists are meant to be short windows. Link each category heading or a View all link to the term archive, which has real pagination and a crawlable address. If the number of categories is large, paginate the outer terms loop instead by setting its Number and pointing a Pagination element at it.
Can Bricks Query Filters filter the posts inside each category?
The documentation lists deeply nested query targets as unsupported and says filters target the outer supported query layer. A filter can narrow which categories the outer terms loop shows. For a word search inside the lists, use a small client-side script over the rendered items. For a site-wide search, use a separate posts loop with Filter - Search and Live Search.
Do I need code execution enabled in Bricks?
Not for the builder-only approach. It is needed for the Query editor (PHP) and for calling PHP functions through the echo tag, as in the grouped array method. Bricks signs executable code and refuses to run it if the signature is missing or invalid. Enable code execution for as few trusted users as possible, and keep the PHP focused on returning data or query arguments.
Will a page cache hide the cost of a nested loop?
It hides it from visitors who receive cached HTML. It does not hide it from the first request after a purge, from logged-in users who bypass the cache, or from the builder. A heavy nested loop can look fine in production and still feel slow when you edit it. Measure the query count as an administrator, with the cache bypassed, and again with the cache on.
Is a transient a safe way to store the grouped data?
It is safe when you control invalidation. Delete it on post saves, post deletes and term changes, give it a sensible expiry as a backstop, keep the stored array small and escape what you store. On a multilingual site, include the language in the transient key so one language's titles are not served to another. If you cannot guarantee invalidation, prefer nested loops with caps.



