Filtering a list of posts looks like a front-end problem until you try to ship it. The search box works, the category chips work, and then a visitor copies the address bar to send the filtered list to a colleague, and the colleague sees the unfiltered page. Or they press Back and leave the site instead of undoing the last filter. Or a screen reader user changes a dropdown and nothing tells them the list has changed. All three failures have the same root: the filter state lives in JavaScript memory instead of in the address.
The single most important idea in this tutorial is that the URL is the state. If every filter the visitor sets is written into the query string, and the server builds the result from that query string, then sharing, bookmarking, reloading, the back button and even a browser with no JavaScript all work, because each of them reduces to loading an address. JavaScript then becomes an optimisation rather than a requirement: instead of reloading the whole page, it fetches the same address, swaps the results in and keeps the address bar in step.
This guide builds that for a Bricks Builder query loop, from scratch and with complete code. On the server, a short PHP filter reads the parameters and turns them into query arguments for one specific loop, and a shortcode renders the form from the same parameters so the controls always match the URL. In Bricks, a handful of ordinary elements provide the wrapper, the loop, a results summary and pagination. In the browser, about a hundred lines of vanilla JavaScript handle the fetch, the swap, the history and the announcements for assistive technology. The filters covered are a text search, category chips, a meta filter, a date filter and a sort control.
You will also see where this approach stops being the right one. Current versions of Bricks include their own query filter elements, with URL parameters, browser history, AJAX updates, a filter index and live search. Those are the better choice for many sites, and the later section on choosing between the two gives a decision rule. Building your own is worthwhile when you need a fixed, human-readable URL shape, query logic the built-in elements do not offer, or full control of the markup.
A few honest boundaries. This is a general guide built from the public Bricks documentation, WordPress core behaviour and web platform standards, not a test report, and it contains no benchmark numbers. Where the Bricks documentation confirms a control, setting or hook, the text uses its name. Where it does not, the text describes the goal and tells you where to look, because labels change between versions. Every PHP example sanitises its input and escapes its output. The JavaScript runs without a library, and the form still works as a plain page navigation if the script fails to load.
Key points
- Put every filter in the query string and build the results from it on the server, so JavaScript only makes updates faster instead of holding the state.
- Prefix your parameter names so they cannot collide with WordPress query variables such as s, year, cat or order.
- Read parameters with an allow-list: sanitise text, validate dates, whitelist sort and meta values, and cap lengths and counts.
- Use the bricks/posts/query_vars filter, scoped to one loop by its element ID, to turn parameters into query arguments without enabling code execution in the builder.
- Use pushState for discrete changes, replaceState while typing, and restore the form from the URL on popstate so the back button behaves.
- Keep a persistent live region outside the swapped area, never steal focus, and mark the results as busy while they load.
- Bricks has built-in Query Filters with URL parameters, history and an index; prefer them unless you need a fixed URL shape or custom logic, and never run both on the same loop.
Why the URL should hold the filter state
Think about what a visitor expects from a filtered list. They expect to be able to copy the address and send it. They expect Back to undo the last change, not to leave the page. They expect a refresh to show the same list. They expect it to work on a flaky mobile connection where the script did not finish loading. A filter that keeps its state only in JavaScript variables fails every one of those tests, and fixing each failure separately leads to a tangle of special cases.
Put the state in the address and most of those requirements disappear. A filtered list is then simply a page at a particular URL. The server reads the query string, builds the query and renders the matching posts, exactly as it does for any other request. Sharing and bookmarking work because they copy the address. Refresh works because it loads the address again. Without JavaScript, a plain GET form submits to the same address with the right parameters and the result is the same. The back button works because every meaningful change is a history entry whose URL fully describes the state.
The rule for what belongs in the URL is easy to apply. If a different value would show the visitor a different list, it belongs in the URL: the search words, the selected topics, the level, the date and the sort order, and the page number. If it is purely presentational and does not change the list, it does not: whether a dropdown is open, where the page is scrolled, which tab of a filter panel is showing.
JavaScript earns its place by making updates fast. When a visitor ticks a topic, the script builds the new query string, requests that address in the background, takes the results region out of the response and puts it into the current page, then updates the address bar. The visitor sees the list change without a reload, the address stays truthful, and if the request fails the script simply navigates to the same address, so the worst case is an ordinary page load. That order of priorities, server first and script second, is the design principle behind everything that follows.
Bricks itself follows the same principle for its built-in query filters. The Bricks documentation says those elements can read filter values from URL parameters on page load, track changes in the browser history so the back and forward buttons move between filter states, and refresh the target loop through an AJAX request. The difference in this tutorial is that you own every piece, which is more work and gives more control over the URL and the query.
One filter change, from click to updated results
- Visitor changes a controlA chip, a select, the search box or the date field
- Script builds the query stringOnly non-default values, for example f_topic and f_sort
- Script fetches the same page URLWith that query string and an abort signal for older requests
- WordPress renders the pageBricks builds the loop query and calls bricks/posts/query_vars
- Your PHP reads the parametersSanitised and allow-listed values become query arguments
- Script swaps the results regionIt updates the live region, then pushes the new URL into history
The parameters we will use, and the names to avoid
Before writing code, fix the contract between the form, the URL and the query. The tutorial’s list is a resources page of guides, with search, topics from the category taxonomy, a level stored in a custom field, a published-since date and a sort order. Each filter gets one parameter, and every parameter name starts with a short prefix, here f_.
The prefix is not decoration. WordPress reserves a set of public query variables, and several of the obvious names for filters are on the list. A search box called s makes WordPress treat the request as a search results page, which loads a different template than your page. A parameter named year, cat, tag, order, orderby, author or name can alter the main query for the request and lead to a 404 or a wrong template on an ordinary page. The page number variable paged belongs to WordPress too. Choosing names that WordPress and other plugins will never use removes a class of strange bugs before they start.
The other design decision is the shape of multi-value parameters. A group of topic chips can send repeated parameters with brackets, such as f_topic[]=news&f_topic[]=guides, which is what a plain HTML form does and what PHP parses into an array. It is also long and ugly once encoded. The script in this tutorial writes the same choice as f_topic=news,guides, a single comma separated value. The PHP side accepts both forms, so the no-JavaScript fallback and the enhanced version produce working, if differently shaped, addresses.
The table in the figure is the whole contract. The central rule is to keep defaults out of the URL: a sort of newest is the default, so it is omitted, and an empty search is omitted. That keeps addresses short, makes the unfiltered page and the URL without parameters identical, and lets you detect “no filters active” by checking whether the query string is empty.
Finally, decide the limits now, because each one will become a line of validation. The search text is capped at 80 characters. At most ten topics are accepted. The level must be one of three known values. The date must be a real calendar date in year-month-day form. The sort must be one of three known values. Anything else is ignored rather than rejected, so a bad or stale address simply shows the unfiltered list instead of an error page.
The parameter contract
| Parameter | Becomes in the query | |
|---|---|---|
| Search | f_q | The s argument, capped at 80 characters |
| Topics | f_topic (comma list) | A taxonomy query on category slugs, up to ten, matching any |
| Level | f_level | A meta query where the level key equals one of three allowed values |
| Published since | f_since | A date query for posts on or after that calendar date |
| Sort | f_sort | An order by list with the post ID as a tie-breaker |
The Bricks page structure: wrapper, loop, summary and pager
The page needs six parts, and none of them requires anything beyond standard Bricks elements. Build the structure first and give each part a hook for the script to find. For hooks, Bricks documents custom HTML attributes: open an element’s Style tab, find the Attributes group, and add a name and a value. The attribute lands on the element’s root node, and values can even use dynamic data.
- The filter form. Add a Shortcode element containing
[guide_filters]. The Bricks documentation describes the Shortcode element as running any registered WordPress shortcode, which is where the next sections render the form. Rendering it on the server means every control already reflects the URL when the page loads. - The results wrapper. Add a Div and give it a custom attribute named
data-gf-results. This is the region the script replaces. Everything the visitor should see change goes inside it. - The active filters. Inside the wrapper, add a second Shortcode element containing
[guide_active_filters]. It prints one removable chip per active filter, and the next sections build it. Because it sits inside the wrapper, it is replaced with every update and always matches the URL. - The results summary. Inside the wrapper, add a Query Results Summary element, point its query setting at the loop, and give it a custom attribute named
data-gf-summary. Bricks documents placeholders for the start, end and total counts and separate texts for one result and no results, so the message reads naturally. The script copies this text into the live region. - The loop. Inside the wrapper, add the container that will repeat for each guide and switch on its Use Query Loop setting. Choose the Posts type, set a realistic posts per page, and use the No Results setting for the empty state. Inside the loop element, build the card from dynamic data such as the title, excerpt and featured image.
- The pager. Inside the wrapper, add a Pagination element, choose the loop in its query setting, and give it a custom attribute named
data-gf-pager. It is optional, and the later section on pagination explains the interaction.
You also need the loop’s element ID, because the PHP filter must act on this loop and no other. The Bricks documentation says every element has a unique ID, shown when you edit it, in the class input as the element’s HTML ID. It looks like #brxe-abc123, and the six characters after the prefix are what PHP receives. Copy them into a constant at the top of the plugin and comment what they refer to.
Two practical notes. First, the whole results wrapper, including the summary and the pager, is swapped on each update, so keep anything that must survive an update, such as the form and its live region, outside it. Second, if a performance plugin strips HTML comments from the page, check that Bricks loop markers survive. The documentation warns that features such as AJAX pagination depend on those comments, and while this tutorial’s fetch and swap does not need them, you may add Bricks AJAX features later.
Page structure, top to bottom
Read the parameters on the server and filter the loop
The server side has two jobs: turn the query string into a clean, validated set of values, and apply those values to exactly one Bricks loop. The first block of the plugin file does both. It starts with a plugin header, a constant that names the loop and a couple of option lists that the form will reuse later.
<?php
/**
* Plugin Name: Guide Filters
* Description: URL based filters for one Bricks query loop.
* Text Domain: guide-filters
*/
defined( 'ABSPATH' ) || exit;
// Six character ID of the Bricks loop element that lists the guides, and the slug of its page.
const GF_LOOP_ID = 'abc123';
const GF_PAGE_SLUG = 'guides';
function gf_sort_options() {
return [
'newest' => __( 'Newest first', 'guide-filters' ),
'oldest' => __( 'Oldest first', 'guide-filters' ),
'title' => __( 'Title A to Z', 'guide-filters' ),
];
}
function gf_level_options() {
return [
'beginner' => __( 'Beginner', 'guide-filters' ),
'intermediate' => __( 'Intermediate', 'guide-filters' ),
'advanced' => __( 'Advanced', 'guide-filters' ),
];
}
/**
* Read and validate the filter parameters. Anything unknown or malformed is ignored.
*/
function gf_params() {
// Read-only filtering on a public page changes no state, so no nonce is needed.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$get = wp_unslash( $_GET );
$params = [
'q' => '',
'topics' => [],
'level' => '',
'since' => '',
'sort' => 'newest',
];
if ( isset( $get['f_q'] ) && is_string( $get['f_q'] ) ) {
$params['q'] = mb_substr( sanitize_text_field( $get['f_q'] ), 0, 80 );
}
if ( isset( $get['f_topic'] ) ) {
$raw = is_array( $get['f_topic'] ) ? $get['f_topic'] : explode( ',', (string) $get['f_topic'] );
$slugs = [];
foreach ( $raw as $item ) {
if ( is_string( $item ) && '' !== trim( $item ) ) {
$slugs[] = sanitize_title( $item );
}
}
$params['topics'] = array_slice( array_values( array_unique( array_filter( $slugs ) ) ), 0, 10 );
}
if ( isset( $get['f_level'] ) && is_string( $get['f_level'] ) && array_key_exists( $get['f_level'], gf_level_options() ) ) {
$params['level'] = $get['f_level'];
}
if ( isset( $get['f_since'] ) && is_string( $get['f_since'] )
&& preg_match( '/^(\d{4})-(\d{2})-(\d{2})$/', $get['f_since'], $m )
&& checkdate( (int) $m[2], (int) $m[3], (int) $m[1] ) ) {
$params['since'] = $get['f_since'];
}
if ( isset( $get['f_sort'] ) && is_string( $get['f_sort'] ) && array_key_exists( $get['f_sort'], gf_sort_options() ) ) {
$params['sort'] = $get['f_sort'];
}
return $params;
}
function gf_has_filters( array $p ) {
return '' !== $p['q'] || $p['topics'] || '' !== $p['level'] || '' !== $p['since'] || 'newest' !== $p['sort'];
}
/**
* Add a clause to an existing tax_query or meta_query without disturbing what the loop already has.
*/
function gf_and( $existing, array $clause ) {
if ( empty( $existing ) ) {
return [ $clause ];
}
return [ 'relation' => 'AND', (array) $existing, $clause ];
}
add_filter( 'bricks/posts/query_vars', function ( $query_vars, $settings, $element_id, $element_name ) {
if ( GF_LOOP_ID !== $element_id ) {
return $query_vars;
}
$p = gf_params();
if ( '' !== $p['q'] ) {
$query_vars['s'] = $p['q'];
}
if ( $p['topics'] ) {
$query_vars['tax_query'] = gf_and(
isset( $query_vars['tax_query'] ) ? $query_vars['tax_query'] : [],
[
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $p['topics'],
'operator' => 'IN',
]
);
}
if ( '' !== $p['level'] ) {
$query_vars['meta_query'] = gf_and(
isset( $query_vars['meta_query'] ) ? $query_vars['meta_query'] : [],
[
'key' => 'level',
'value' => $p['level'],
'compare' => '=',
]
);
}
if ( '' !== $p['since'] ) {
$query_vars['date_query'] = [ [ 'after' => $p['since'], 'inclusive' => true ] ];
}
$orders = [
'newest' => [ 'date' => 'DESC', 'ID' => 'DESC' ],
'oldest' => [ 'date' => 'ASC', 'ID' => 'ASC' ],
'title' => [ 'title' => 'ASC', 'ID' => 'ASC' ],
];
unset( $query_vars['order'] );
$query_vars['orderby'] = $orders[ $p['sort'] ];
return $query_vars;
}, 10, 4 );
Walking through it. gf_params is the only place that touches $_GET. Each value is checked by type first, because a request can send an array where you expect a string, and then cleaned. The search text goes through sanitize_text_field and a length cap. Topic slugs are cleaned with sanitize_title, deduplicated and limited to ten. The level and sort values must be keys of the allowed lists, and the date must match the year-month-day pattern and pass checkdate, so 2026-02-31 is rejected. Whatever fails validation is dropped, which is why a hand-edited address never produces an error.
The filter is the bridge to Bricks. The Bricks documentation describes bricks/posts/query_vars as the filter that receives the query arguments, the element settings, the element ID and the element name before the query runs. The first line returns early for every loop except yours, so other queries on the site are untouched. The helper gf_and adds a clause to any taxonomy or meta query the loop already defines, nesting it under an AND relation, so settings made in the builder keep working alongside the URL filters. Sorting uses an array of order keys with the post ID last. That tie-breaker matters whenever many posts share the same date or title, because without it, paginated results can repeat or skip posts, and the Bricks documentation recommends exactly this for multiple ordering criteria.
The filter changes only the query. It does not require code execution in Bricks, nothing in the builder holds PHP, and the code can live in version control. The alternative the documentation offers is the Query editor control, which returns query arguments from PHP typed into the builder, but that needs code execution enabled and a valid code signature on the saved code, which is a heavier requirement for the same result. There is also a documented dynamic data tag that reads a URL parameter. It is handy for showing a value or driving a condition, but among the documented query controls there is no way to say that a row should be skipped when its parameter is missing, while PHP can leave the clause out entirely.
Render the form from the same parameters
The form is a shortcode, which the Bricks Shortcode element runs. Rendering on the server has a decisive advantage: the controls start in the state the URL describes, so a shared link, a refresh and the no-JavaScript case all show correct checked boxes and filled fields without any script. The markup uses only native controls, which bring keyboard support, touch behaviour and screen reader semantics for free.
add_shortcode( 'guide_filters', function () {
$p = gf_params();
$action = get_permalink( get_queried_object_id() );
$action = $action ? $action : home_url( '/' );
$terms = get_terms( [ 'taxonomy' => 'category', 'hide_empty' => true ] );
$terms = is_wp_error( $terms ) ? [] : $terms;
ob_start();
?>
<form class="gf" data-gf method="get" role="search"
action="<?php echo esc_url( $action ); ?>"
aria-label="<?php esc_attr_e( 'Filter guides', 'guide-filters' ); ?>">
<div class="gf__field">
<label for="gf-q"><?php esc_html_e( 'Search guides', 'guide-filters' ); ?></label>
<input type="search" id="gf-q" name="f_q" maxlength="80" autocomplete="off"
value="<?php echo esc_attr( $p['q'] ); ?>">
</div>
<fieldset class="gf__chips">
<legend><?php esc_html_e( 'Topics', 'guide-filters' ); ?></legend>
<?php foreach ( $terms as $term ) : ?>
<label class="gf__chip">
<input type="checkbox" name="f_topic[]" value="<?php echo esc_attr( $term->slug ); ?>"
<?php checked( in_array( $term->slug, $p['topics'], true ) ); ?>>
<span><?php echo esc_html( $term->name ); ?></span>
</label>
<?php endforeach; ?>
</fieldset>
<div class="gf__field">
<label for="gf-level"><?php esc_html_e( 'Level', 'guide-filters' ); ?></label>
<select id="gf-level" name="f_level">
<option value=""><?php esc_html_e( 'Any level', 'guide-filters' ); ?></option>
<?php foreach ( gf_level_options() as $value => $label ) : ?>
<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $p['level'], $value ); ?>>
<?php echo esc_html( $label ); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="gf__field">
<label for="gf-since"><?php esc_html_e( 'Published since', 'guide-filters' ); ?></label>
<input type="date" id="gf-since" name="f_since" value="<?php echo esc_attr( $p['since'] ); ?>">
</div>
<div class="gf__field">
<label for="gf-sort"><?php esc_html_e( 'Sort by', 'guide-filters' ); ?></label>
<select id="gf-sort" name="f_sort" data-default="newest">
<?php foreach ( gf_sort_options() as $value => $label ) : ?>
<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $p['sort'], $value ); ?>>
<?php echo esc_html( $label ); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="gf__actions">
<button type="submit"><?php esc_html_e( 'Apply filters', 'guide-filters' ); ?></button>
<a class="gf__reset" href="<?php echo esc_url( $action ); ?>" data-gf-reset>
<?php esc_html_e( 'Reset', 'guide-filters' ); ?>
</a>
</div>
<p class="gf__status" role="status" aria-live="polite" data-gf-status></p>
</form>
<?php
return ob_get_clean();
} );
What matters in the markup. The form uses method="get" and points at the page’s own permalink, so submitting it without JavaScript produces exactly the kind of URL the server code reads. Every control has a visible label tied to it by for and id, and the topic chips sit in a fieldset with a legend, so a screen reader announces the group name with each checkbox. The chips are real checkboxes, with the visible pill drawn by CSS on the following span, which keeps them focusable and operable with the space bar. The checked, selected and value attributes are all produced by escaped output, so a hand-built URL cannot inject markup.
The last paragraph of the form is the live region. It is empty on load and has role="status", which assistive technology treats as a polite announcement area. It sits in the form, outside the results wrapper, so it persists across updates, which is what lets screen readers notice its text changing. The two data attributes, data-gf on the form and data-gf-reset on the reset link, are the hooks the script uses, and data-default on the sort select tells the script which value is the default and should be left out of the URL.
The reset control is a real link to the unfiltered page, not a button that clears fields, so it works without JavaScript and it is announced as navigation. Finally, the shortcode is called through the Bricks Shortcode element, which the documentation describes as supporting dynamic data in its field. The shortcode needs none, so it is entered exactly as shown.
The JavaScript: fetch the same URL and swap the results
Now the enhancement layer. Save the script as guide-filters.js next to the plugin file and load it only on the filter page, with the PHP below the script. It needs no library. It finds the form and the results region by their data attributes, and if either is missing, or the browser lacks fetch, it does nothing, leaving the plain form to work by itself.
(function () {
'use strict';
var form = document.querySelector('[data-gf]');
var results = document.querySelector('[data-gf-results]');
if (!form || !results || !('fetch' in window) || !('URLSearchParams' in window)) {
return; // The plain GET form still works without this script.
}
var status = form.querySelector('[data-gf-status]');
var basePath = new URL(form.action, window.location.href).pathname;
var reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var current = window.location.pathname + window.location.search;
var controller = null;
var timer = null;
var typing = false;
results.setAttribute('tabindex', '-1');
// Form state to a query string. Empty values and defaults are left out.
function paramsFromForm() {
var params = new URLSearchParams();
var topics = [];
new FormData(form).forEach(function (raw, key) {
var value = String(raw).trim();
if (!value) { return; }
if (key === 'f_topic[]') { topics.push(value); return; }
var field = form.elements.namedItem(key);
if (field && field.dataset && field.dataset.default === value) { return; }
params.set(key, value);
});
if (topics.length) { params.set('f_topic', topics.join(',')); }
return params;
}
function toUrl(params) {
var query = params.toString().replace(/%2C/g, ',');
return basePath + (query ? '?' + query : '');
}
// Query string back to the controls, used for Back, Forward and Reset.
function applyParamsToForm(params) {
var topics = (params.get('f_topic') || '').split(',').concat(params.getAll('f_topic[]'));
Array.prototype.forEach.call(form.elements, function (el) {
if (!el.name || el.type === 'submit') { return; }
if (el.name === 'f_topic[]') {
el.checked = topics.indexOf(el.value) !== -1;
} else {
var value = params.get(el.name);
el.value = value === null ? (el.dataset.default || '') : value;
}
});
}
// Fetch a URL, swap the results region and optionally write history.
function load(url, historyMode) {
if (controller) { controller.abort(); }
var mine = controller = new AbortController();
results.setAttribute('aria-busy', 'true');
return fetch(url, { signal: mine.signal, credentials: 'same-origin' })
.then(function (response) {
if (!response.ok) { throw new Error('HTTP ' + response.status); }
return response.text();
})
.then(function (html) {
var doc = new DOMParser().parseFromString(html, 'text/html');
var fresh = doc.querySelector('[data-gf-results]');
if (!fresh) { throw new Error('Results region missing from the response'); }
results.replaceChildren.apply(results, Array.prototype.slice.call(fresh.childNodes));
var summary = results.querySelector('[data-gf-summary]');
status.textContent = summary ? summary.textContent.trim() : '';
if (historyMode === 'push') { history.pushState({ gf: true }, '', url); }
if (historyMode === 'replace') { history.replaceState({ gf: true }, '', url); }
current = url;
})
.catch(function (error) {
if (error.name === 'AbortError') { return; }
window.location.assign(url); // Fall back to a normal page load.
})
.then(function () {
if (controller === mine) { results.removeAttribute('aria-busy'); }
});
}
function applyFilters(historyMode) {
var url = toUrl(paramsFromForm());
if (url === current) { return false; }
load(url, historyMode);
return true;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
window.clearTimeout(timer);
typing = false;
applyFilters('push');
});
form.addEventListener('change', function (event) {
if (event.target.type === 'search') { return; }
window.clearTimeout(timer);
typing = false;
applyFilters('push');
});
// While typing: the first update adds a history entry, later ones replace it.
form.addEventListener('input', function (event) {
if (event.target.type !== 'search') { return; }
window.clearTimeout(timer);
timer = window.setTimeout(function () {
if (applyFilters(typing ? 'replace' : 'push')) { typing = true; }
}, 350);
});
form.addEventListener('click', function (event) {
if (!event.target.closest('[data-gf-reset]')) { return; }
event.preventDefault();
typing = false;
applyParamsToForm(new URLSearchParams());
applyFilters('push');
});
window.addEventListener('popstate', function () {
var url = window.location.pathname + window.location.search;
if (url === current) { return; } // A fragment-only change: nothing to reload.
typing = false;
applyParamsToForm(new URLSearchParams(window.location.search));
load(url, null);
});
// Pager links and active filter chips inside the results: fetch instead of navigating.
results.addEventListener('click', function (event) {
var link = event.target.closest('[data-gf-pager] a, [data-gf-active] a');
if (!link || !link.getAttribute('href') || event.defaultPrevented || event.button !== 0 ||
event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { return; }
var target = new URL(link.href, window.location.href);
if (target.origin !== window.location.origin) { return; }
event.preventDefault();
applyParamsToForm(target.searchParams);
load(target.pathname + target.search, 'push').then(function () {
results.focus({ preventScroll: true });
results.scrollIntoView({ behavior: reduceMotion ? 'auto' : 'smooth', block: 'start' });
});
});
})();
Reading the script in order. paramsFromForm reads every control with FormData, skips empty values and defaults, and gathers the topic checkboxes into one comma separated value. toUrl prints the query string with commas left readable and always starts from the page’s own path, which is also how a visitor on page two of the results gets back to page one when a filter changes. applyParamsToForm does the reverse for Back, Forward and Reset.
load is the heart of it. It aborts any request still in flight, so a slow response can never overwrite a newer one. It requests the target URL, parses the response into a separate document, finds the results region in it and moves those nodes into the live page. Nothing from the response is executed, because a document made by DOMParser does not run scripts, and only the nodes inside the results region are used. After a successful swap it copies the summary text into the live region and writes history. If anything fails, the catch block sends the browser to the URL, so the visitor still gets the right page. The final step clears the busy flag only if no newer request has started.
The listeners wire it together. Submit and change events apply the filters and push a history entry. Typing is debounced for 350 milliseconds and handled separately, which the next section explains. The reset link is intercepted, but because it is a real link, a visitor without the script follows it normally. The listener for pager links and active filter chips sits on the results element, which survives every swap, so it keeps working after the children are replaced. It also writes the clicked link’s parameters back into the controls, and it moves focus to the results container, because the link the visitor just activated no longer exists after the swap.
The PHP that loads the script belongs in the same plugin. It skips the Bricks builder panel, as the Bricks child theme documentation advises for scripts and styles, and loads the file only on the filter page, in the footer, with a version taken from the file’s modification time.
add_action( 'wp_enqueue_scripts', function () {
if ( ( function_exists( 'bricks_is_builder_main' ) && bricks_is_builder_main() ) || ! is_page( GF_PAGE_SLUG ) ) {
return;
}
$file = plugin_dir_path( __FILE__ ) . 'guide-filters.js';
if ( ! is_readable( $file ) ) {
return;
}
wp_enqueue_script(
'guide-filters',
plugin_dir_url( __FILE__ ) . 'guide-filters.js',
[],
filemtime( $file ),
[ 'in_footer' => true, 'strategy' => 'defer' ]
);
} );
If you would rather not maintain a file, Bricks documents page-level custom code in the page settings, where the script can live and load only on that page. A file is easier to version and review.
History: push, replace and the back button
The history logic is small, and it is where most home-made filters feel wrong, so it deserves its own explanation. The browser keeps a list of entries. pushState adds an entry and replaceState rewrites the current one. The popstate event fires when the visitor moves between entries with Back or Forward, and at that moment the page must put itself into the state the entry’s URL describes.
Which method to use depends on the kind of change. A discrete choice, such as ticking a topic, picking a sort order or submitting the search, is a step the visitor may want to undo, so it gets a new entry with pushState. Typing is different. If every pause in typing added an entry, Back would walk through half-typed words one by one. The script therefore pushes one entry when typing starts and replaces that entry as the text grows, so a single Back removes the whole search. The typing flag tracks this, and it resets on any other action.
The popstate handler does three things: it compares the address with the last one the script loaded, writes the entry’s query string back into the controls, and loads the results without touching history. The comparison matters because browsers also fire popstate for in-page anchor links, and reloading the results for a link to a heading would be wasteful and visibly flickery. Restoring the controls matters because without it, Back would show the old results beside the new control state, which is confusing and a quiet accessibility problem.
Two edge cases deserve a test. The first is the browser’s back and forward cache. When a visitor leaves the page and returns with Back, the browser may restore the whole page from memory, including the swapped results, which is correct as long as the URL in the address bar matches. The second is arriving at an address with a filter already in it, such as a shared link. Nothing runs in that case, because the server rendered the form and the results from the same parameters. That is the benefit of putting state in the URL first.
The state object passed to the history calls is a tiny flag. Do not store results or large data in it. The URL is the state, and the state object adds nothing the address does not already say. Keeping that discipline means a copied URL, a bookmarked URL and a history entry all produce the same page.
What the history stack looks like during one visit
Style the filter bar: chips, fields and focus
The form works at this point but looks like default browser controls. The styling job has three goals: comfortable touch targets, a layout that reflows on narrow screens, and a visible focus indicator on every control. Add the CSS below to the site’s global stylesheet or to the page’s custom CSS. Bricks documents places for both, and a plugin or child theme stylesheet works equally well.
.gf {
display: grid;
gap: 1rem 1.25rem;
grid-template-columns: repeat(auto-fit, minmax(13rem, 1fr));
align-items: end;
padding: 1.25rem;
border: 1px solid #c9d0da;
border-radius: 14px;
background: #f7f8fa;
}
.gf__field { display: grid; gap: 0.35rem; }
.gf label,
.gf legend { font-size: 0.875rem; font-weight: 600; color: #1c2430; }
.gf input[type="search"],
.gf input[type="date"],
.gf select {
width: 100%;
min-height: 2.75rem;
padding: 0.5rem 0.75rem;
border: 1px solid #6b7686;
border-radius: 8px;
background: #fff;
font: inherit;
color: inherit;
}
.gf :is(input, select, button, a):focus-visible {
outline: 3px solid #2f5fd0;
outline-offset: 2px;
}
.gf__chips {
grid-column: 1 / -1;
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin: 0;
padding: 0;
border: 0;
}
.gf__chips legend { width: 100%; padding: 0; margin-bottom: 0.4rem; }
.gf__chip { position: relative; }
.gf__chip input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
cursor: pointer;
}
.gf__chip span {
display: inline-block;
padding: 0.45rem 0.95rem;
border: 1px solid #6b7686;
border-radius: 999px;
background: #fff;
font-size: 0.9375rem;
}
.gf__chip input:checked + span {
background: #1c2430;
border-color: #1c2430;
color: #fff;
}
.gf__chip input:checked + span::before { content: "\2713\00a0"; }
.gf__chip input:focus-visible + span {
outline: 3px solid #2f5fd0;
outline-offset: 2px;
}
.gf__actions { display: flex; align-items: center; gap: 1rem; }
.gf button[type="submit"] {
min-height: 2.75rem;
padding: 0.5rem 1.25rem;
border: 0;
border-radius: 8px;
background: #2f5fd0;
color: #fff;
font: inherit;
font-weight: 600;
cursor: pointer;
}
.gf__reset { color: #2f5fd0; text-underline-offset: 0.2em; }
.gf__status { grid-column: 1 / -1; margin: 0; min-height: 1.5em; font-size: 0.9375rem; color: #3a4556; }
[data-gf-results][aria-busy="true"] { opacity: 0.55; transition: opacity 0.15s; }
@media (prefers-reduced-motion: reduce) {
[data-gf-results][aria-busy="true"] { transition: none; }
}
What the important rules do. The outer grid uses auto-fit with a minimum column width, so the controls sit in a row on a wide screen and stack on a phone without a single media query. The fields, selects and button are at least 2.75rem tall, which is comfortably above the 24 pixel minimum that WCAG 2.2 sets for pointer targets and closer to what thumbs need. The shared :focus-visible rule draws a three pixel outline only when the browser decides a focus ring is useful, which means keyboard users see it and mouse users are not distracted.
The chip pattern needs a closer look because it is the part people get wrong. The checkbox is not hidden. It is stretched over the whole chip with inset: 0 and made invisible with opacity: 0, so it stays in the tab order, in the accessibility tree and under the visitor’s finger. Removing it with display: none or visibility: hidden would make the control unreachable by keyboard and invisible to screen readers. The visible pill is the span that follows the input, and the sibling selectors :checked + span and :focus-visible + span restyle it. A checkmark added with ::before means the checked state does not rely on colour alone, which also helps in forced colours modes where backgrounds may be dropped.
The last two rules cover the busy state. While a request is in flight the script sets aria-busy on the results region, and the CSS fades it slightly so sighted visitors see that an update is underway. Visitors who ask their system for reduced motion get no transition. Nothing is hidden or collapsed during loading, so the layout does not jump.


Active filters and the empty state
Two pieces of feedback make a filtered list feel finished: a visible summary of what is currently applied, with a one-click way to remove each filter, and a helpful message when nothing matches. Both can be built on the same server-side parameters, and both live inside the results wrapper so they refresh with every update.
The active filters are a list of links. Each link points at the current page with that one filter removed, so it works without JavaScript, and the script from earlier intercepts it when available. Add a helper that builds an address from a set of parameters, and a second shortcode that prints one chip per active filter. Put the shortcode in the Shortcode element you placed above the summary.
function gf_base_url() {
$url = get_permalink( get_queried_object_id() );
return $url ? $url : home_url( '/' );
}
function gf_url( array $p ) {
$args = [];
if ( '' !== $p['q'] ) { $args['f_q'] = $p['q']; }
if ( $p['topics'] ) { $args['f_topic'] = implode( ',', $p['topics'] ); }
if ( '' !== $p['level'] ) { $args['f_level'] = $p['level']; }
if ( '' !== $p['since'] ) { $args['f_since'] = $p['since']; }
if ( 'newest' !== $p['sort'] ) { $args['f_sort'] = $p['sort']; }
if ( ! $args ) {
return gf_base_url();
}
// add_query_arg does not encode new values, so encode them first.
$url = add_query_arg( array_map( 'rawurlencode', $args ), gf_base_url() );
return str_replace( '%2C', ',', $url );
}
add_shortcode( 'guide_active_filters', function () {
$p = gf_params();
$chips = [];
if ( '' !== $p['q'] ) {
$chips[] = [ sprintf( __( 'Search: %s', 'guide-filters' ), $p['q'] ), array_merge( $p, [ 'q' => '' ] ) ];
}
foreach ( $p['topics'] as $slug ) {
$term = get_term_by( 'slug', $slug, 'category' );
if ( $term ) {
$rest = array_values( array_diff( $p['topics'], [ $slug ] ) );
$chips[] = [ sprintf( __( 'Topic: %s', 'guide-filters' ), $term->name ), array_merge( $p, [ 'topics' => $rest ] ) ];
}
}
if ( '' !== $p['level'] ) {
$levels = gf_level_options();
$chips[] = [ sprintf( __( 'Level: %s', 'guide-filters' ), $levels[ $p['level'] ] ), array_merge( $p, [ 'level' => '' ] ) ];
}
if ( '' !== $p['since'] ) {
$chips[] = [ sprintf( __( 'Since: %s', 'guide-filters' ), $p['since'] ), array_merge( $p, [ 'since' => '' ] ) ];
}
if ( ! $chips ) {
return '';
}
ob_start();
?>
<ul class="gf-active" data-gf-active>
<?php foreach ( $chips as $chip ) : ?>
<li>
<a href="<?php echo esc_url( gf_url( $chip[1] ) ); ?>"
aria-label="<?php echo esc_attr( sprintf( __( 'Remove filter: %s', 'guide-filters' ), $chip[0] ) ); ?>">
<?php echo esc_html( $chip[0] ); ?> <span aria-hidden="true">×</span>
</a>
</li>
<?php endforeach; ?>
<li><a class="gf-active__clear" href="<?php echo esc_url( gf_base_url() ); ?>"><?php esc_html_e( 'Clear all', 'guide-filters' ); ?></a></li>
</ul>
<?php
return ob_get_clean();
} );
How it works. gf_url is the inverse of gf_params: it prints only the non-default values, in the same shape the script writes. Each chip carries a copy of the current parameters with one entry cleared, so a chip is just a link to the page with that filter removed. The visible text is escaped with esc_html, the address with esc_url, and the accessible name says what activating the chip does, since the visible multiplication sign alone means nothing to a screen reader and is hidden from it. When no filter is active the shortcode prints nothing at all.
The empty state is where Bricks does most of the work. The Bricks documentation says each query loop can show fallback content when no results match, using either a short No Results text or, where available, a no-results template, and the Query Results Summary element has its own text for zero results and for exactly one result. Use a template when you want more than a sentence. Good empty state content does four things: it says plainly that nothing matched, it keeps the active filters visible above it so the visitor can see why, it offers a way out with the Clear all link, and it suggests a broader search. Because the active filters shortcode sits outside the loop but inside the wrapper, it stays on screen when the loop itself is empty.
.gf-active { display: flex; flex-wrap: wrap; gap: 0.5rem; margin: 1rem 0; padding: 0; list-style: none; }
.gf-active a {
display: inline-block;
padding: 0.35rem 0.8rem;
border: 1px solid #2f5fd0;
border-radius: 999px;
background: #eef3ff;
color: #1f3f94;
font-size: 0.9rem;
text-decoration: none;
}
.gf-active a:hover { background: #dfe8ff; }
.gf-active a:focus-visible { outline: 3px solid #2f5fd0; outline-offset: 2px; }
.gf-active__clear { border-color: transparent !important; background: transparent !important; text-decoration: underline !important; }

Accessibility: labels, a live region and focus
Accessibility is not a layer to add at the end of a dynamic filter. The interaction itself, a list that changes without a page load, is exactly the kind that fails assistive technology users when it is not announced. The good news is that most of what is needed has been built in already, and the remaining pieces are small.
Name every control. Each field has a visible label connected by for and id. The topic chips are grouped by a fieldset and legend. The form is a search landmark with an accessible name. Placeholder text is never used as the only label, because it disappears while typing and has weak contrast by default.
Announce the result, not the process. The live region is a paragraph with role="status", which is a polite announcement area. WCAG 2.1 describes status messages in success criterion 4.1.3: a result count that appears without receiving focus should be exposed to assistive technology. The script copies the Query Results Summary text into it, so the visitor hears something like the number of results, or that none were found. Three details make this reliable. The region is present in the page before any update, because a region that is created at the moment of change is often not announced. It lives outside the swapped area so it is never destroyed and rebuilt. And it receives one short message per update, since the search input is debounced, rather than a message for every keystroke.
Mark the busy state. The script sets aria-busy on the results region while a request runs and clears it afterwards. Assistive technology can use this to avoid reading half-updated content, and the CSS fades the region for sighted visitors.
Leave focus alone. The most common accessibility bug in dynamic filters is moving the focus after each change. A visitor ticking three chips with the keyboard must stay on the chips. The script therefore never moves focus after a form change. The one exception is a link inside the results, such as a pager link or an active filter chip. Activating it replaces the element that held focus, so the script moves focus to the results container, which has tabindex="-1" so it can receive programmatic focus without joining the tab order. Scrolling to the results respects the visitor’s reduced motion preference.
Keep the native behaviour. Native checkboxes toggle with the space bar, a search field submits with Enter, and selects open with the arrow keys. Because the script listens to change and submit events instead of key presses, it inherits all of that, including behaviour on touch and with switch devices.
Finish with a manual check. Use only the keyboard to set every filter, remove one with the chip and reset. Zoom the page to 200 percent and confirm nothing overlaps. Turn on a screen reader and listen to what is announced after each change, and test with JavaScript disabled so the plain form still works. These checks take ten minutes and catch the failures automated tools miss.
Meta, date and sort filters done properly
The level filter in the server code is the simplest meta filter: one custom field that stores a plain string, compared for equality against one of three allowed values. That shape generalises, and a few rules keep it fast and correct.
Filter on simple stored values. A meta query compares whole meta values in the database. A text, select or number field stores exactly that, so equality, IN and numeric comparisons work. A field that stores an array, such as a checkbox list, a cloneable group or a relationship, keeps a serialised value that a meta query cannot search reliably. If you need to filter on such a field, mirror the value you need into a flat meta key when the post is saved, as the companion Meta Box tutorial explains, and filter on that key. The Bricks documentation gives the same warning about its own filter elements: values stored as serialised arrays or complex objects are not reliable filter sources.
Match the comparison to the type. For a range filter such as a minimum and maximum reading time, parse both values as numbers, discard anything that is not numeric, and ask for a numeric comparison so that 9 sorts before 10. The snippet below is a drop-in addition to the filter callback from earlier. It reads two extra parameters and builds a BETWEEN clause.
$min = isset( $_GET['f_min'] ) && is_numeric( $_GET['f_min'] ) ? (float) $_GET['f_min'] : null; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$max = isset( $_GET['f_max'] ) && is_numeric( $_GET['f_max'] ) ? (float) $_GET['f_max'] : null; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( null !== $min || null !== $max ) {
$low = null !== $min ? $min : 0;
$high = null !== $max ? $max : 100000;
$query_vars['meta_query'] = gf_and(
isset( $query_vars['meta_query'] ) ? $query_vars['meta_query'] : [],
[
'key' => 'read_minutes',
'value' => [ min( $low, $high ), max( $low, $high ) ],
'compare' => 'BETWEEN',
'type' => 'NUMERIC',
]
);
}
The numbers are cast to floats before they reach the query, so nothing from the URL is ever treated as text, and swapping a reversed minimum and maximum with min and max avoids an empty result caused by a typo. In a real plugin, move the reading of f_min and f_max into gf_params alongside the other parameters so that all validation lives in one place and the form, chips and query all see the same values.
Choose the right date. The published-since filter uses the post’s own publish date through a date query, which WordPress compares in the site’s timezone. If the date that matters is a custom field, such as the date of an event, filter on the field instead, and make sure the stored format sorts and compares correctly. The Bricks documentation notes that a meta query compares the raw stored value and not what a dynamic tag displays, and that an ACF date picker stores its value as digits in year, month, day order regardless of how it is displayed. A Meta Box date field stores whatever its save format says. A field stored as Y-m-d can be filtered like this.
$query_vars['meta_query'] = gf_and(
isset( $query_vars['meta_query'] ) ? $query_vars['meta_query'] : [],
[
'key' => 'event_date',
'value' => $p['since'],
'compare' => '>=',
'type' => 'DATE',
]
);
Keep sorting honest. The sort parameter is a key into a fixed list, never a column name from the URL. Every order includes the post ID as the final tie-breaker, so paging through results never repeats or skips an item. If you sort by a numeric custom field, set the meta key and order by its numeric value. If search relevance matters, WordPress supports a relevance ordering for search queries, which you can offer as a fourth sort option that applies only when a search term is present.
Know what search costs. The default WordPress search looks for the words in titles, content and excerpts, without stemming or typo tolerance. Widening it to custom fields and taxonomy terms is possible but each added field makes the query more expensive, a warning the Bricks documentation gives for its own search criteria. If search quality becomes the main feature, consider the Bricks Search filter with custom criteria or a dedicated search solution rather than stretching a hand-written query.
Pagination, load more and the AJAX caveat
A filtered list of any size needs paging, and paging is where a hand-built filter most often disagrees with the rest of Bricks. Start with what works naturally. The Bricks Pagination element has a setting that selects which query it controls, and the Bricks documentation says its markup is generated by the WordPress function that builds paging links, with a filter that lets you adjust the arguments passed to it. Inside this tutorial’s structure, the pager is part of the results wrapper, so it is replaced with every update and always reflects the current page of the current filter set.
Three rules keep it consistent. First, changing a filter must return the visitor to page one. The script’s address builder always starts from the page’s own path, which removes any page segment, so a new filter never lands on page four of a shorter list. Second, the pager links must carry the filter parameters, or page two would silently drop them. WordPress paging links normally keep the current query string, but confirm it on a real page with filters active by hovering over a page link. If your parameters are missing, the arguments filter that Bricks documents can add them to the paging function’s add_args setting.
add_filter( 'bricks/paginate_links_args', function ( $args ) {
if ( ! is_page( GF_PAGE_SLUG ) ) {
return $args;
}
$query = wp_parse_url( gf_url( gf_params() ), PHP_URL_QUERY );
if ( $query ) {
wp_parse_str( $query, $add_args );
$args['add_args'] = $add_args;
}
return $args;
} );
The callback rebuilds the query string from the validated parameters, never from the raw request, and hands it to the paging function as extra arguments. Third, a stale address must fail gracefully. Someone may share a link to page five of a long list, and by the time it is opened the filter set may match only two pages. WordPress returns no posts for a page beyond the end, so the empty state you built earlier is what the visitor sees, with the active filters and the Clear all link to recover. That is acceptable, and far better than an error.
The attribute data-gf-pager on the Pagination element is what lets the script treat its links as updates instead of page loads. Without that attribute the links work as ordinary navigation, which is a safe default.
Now the caveat. Bricks offers its own AJAX pagination, a Load more button and infinite scroll. The documentation groups these, and the query filters, as Bricks AJAX features, and describes the filter system as sending the selected filter state together with the current page when pagination is AJAX and targets the same query. Those requests go to Bricks, not to your page address. This tutorial’s filter reads its parameters from the address of the request that renders the query, and the documentation does not clearly say how a page’s own URL parameters reach a Bricks AJAX request. Do not assume. Apply a filter, load more results with the Bricks feature, and compare them with the plain page-two link. If the extra results ignore your filters, use normal paging links as above, or use the built-in filter elements, which are designed to pass their state through those requests.
The same test applies to infinite scroll and to any Bricks feature that fetches results separately from the page. A quiet failure here is worse than a visible error, because the list looks fine and simply stops respecting the filter after the first screen.
Your own filter or the built-in Bricks Query Filters
Everything above can also be done, with less code, using the Query Sort, Filter and Live Search feature in current versions of Bricks. It is worth understanding what it offers before you commit to your own, because it is a real alternative and often the better one.
Turn it on in the Bricks settings under the General tab, in the query filters setting, then add elements from the Filter group: Search, Checkbox, Radio, Select, Range, Datepicker, Active Filters and Submit or Reset. Each filter has a target query setting that points at a loop on the page, so filters can sit anywhere, in a sidebar or an offcanvas panel. Filters can apply on input or wait for a submit button. The documentation says the feature reads filter values from URL parameters on page load, using either a generated brx_ parameter or a custom readable name set on the filter, keeps browser history so Back and Forward restore filter states, updates the loop through AJAX, and refreshes dynamic filter elements and restores focus afterwards. It also builds an index in custom database tables so that options and counts can be generated efficiently, which you manage from the same settings area, and it supports a live search mode.
It has limits that matter. It supports loops of posts, terms and users, but not API or array loops, and not loops deeply nested inside other queries. Filter elements should not be placed inside a Bricks component. Custom field filters work best with simple values, and the documentation says serialised arrays and complex objects are not reliable sources by default. Its custom fields integration covers Advanced Custom Fields and Meta Box, with the exception that Meta Box custom table fields are not supported. Because it maintains an index, changes to filter elements and large sites can need a regeneration or background jobs to finish before counts are right. And the documentation warns against combining it with third-party filtering plugins or custom code that forces the same query to run again.
That last warning is the practical rule for this tutorial: choose one mechanism per loop. The URL filter in this guide changes the same query arguments the Bricks filters change, so running both on one loop means two systems fighting over one query.
So which one? Prefer the built-in feature when the filters are standard fields on a post, term or user loop, when you want live counts, a range slider or a date picker, when cards contain Bricks interactive elements that must keep working after an update, or when you want AJAX pagination that stays in step with the filters. Build your own when the URL shape is a requirement, for example a clean, stable address you plan to promote or reference, when the logic goes beyond what the filter elements offer, such as a relationship, a computed value or several post types combined, when you want no index tables or no extra setting enabled, or when you need exact control of the markup and the announcements. For a single search box and a sort control, either route is small. And if the loop is an API or array loop, neither tool applies, so filter at the source.
Own URL filter or built-in Bricks Query Filters
The two approaches side by side
| Built-in Query Filters | Own URL filter | |
|---|---|---|
| Setup | Enable a setting, add Filter elements, pick a target query | A plugin with PHP, a shortcode, a script and a few Bricks elements |
| URL shape | brx_ parameters or a readable name per filter | Any shape you design |
| Prepared data | Index tables for options and counts | None |
| Counts and ranges | Provided | You build them |
| History and focus | Handled by Bricks | You build and test them |
| Custom logic | Hooks for extension | Any query argument you can write |
| Supported loops | Posts, terms and users | A post loop you target by element ID |
Crawlers, caches, abuse and what goes wrong
A filter that works for one visitor can still cause trouble at scale, because every combination of parameters is a separate address. Three groups of problems follow from that, and a fourth is simply bugs.
Crawlers. Five filters with a handful of values each produce thousands of distinct URLs, all showing overlapping lists. Search engines that crawl them waste effort and may index thin or duplicate pages. The simplest control is to ask for filtered views not to be indexed while still letting crawlers follow the links. WordPress core has a filter for the robots meta directives, which the snippet below uses. It adds noindex only when a filter is active, so the unfiltered page stays indexable. Check the page source afterwards, because an SEO plugin may print its own robots directive, and two conflicting ones help nobody. Do not combine this with a robots.txt rule for the same URLs, since a crawler that cannot fetch the page cannot see the noindex. For topics that deserve to rank, such as one category, link to the real category archive, which is a stable, indexable landing page, instead of promoting a parameter combination.
add_filter( 'wp_robots', function ( $robots ) {
if ( is_page( GF_PAGE_SLUG ) && gf_has_filters( gf_params() ) ) {
$robots['noindex'] = true;
$robots['follow'] = true;
}
return $robots;
} );
Caches. Page caches, hosting caches and CDNs treat the query string in different ways. Some key each distinct string as its own entry, some ignore it, and some skip caching when one is present. Test your stack with the filter active and check the headers of the response. If every parameter combination creates a cache entry, a crawler or an attacker can fill the cache with junk, so consider limiting which parameters create entries or excluding them. If the cache ignores the query string, filtered requests would return the unfiltered page, which is a visible bug you will notice immediately.
Abuse. Search is the expensive filter. The server code already caps the search text at 80 characters, allows at most ten topics, accepts only known values for level and sort, and never lets the URL choose the page size. Keep it that way. Do not add a per-page parameter that accepts any number, and do not let any parameter name a meta key or an order column. For a public site under load, add rate limiting at the server or CDN for requests with search parameters, and keep the posts per page modest.
Finally, the bugs. Match the symptom to a likely cause.
- Filters change nothing. The constant does not match the loop’s element ID, the plugin is inactive, or the loop is not a posts query. Recopy the six characters from the element and check that the filter reaches your callback.
- The page filters on reload but not through the script. The response is missing the results wrapper attribute, a performance plugin changed the markup, or the response is a login or cached page. The console message about a missing results region points at it.
- Back shows the wrong controls. The popstate handler did not run or the topic format differs. Make sure the controls are restored from both comma and bracket forms.
- Strange 404 or the wrong template. A parameter name collides with a WordPress query variable. Prefix every name.
- Results repeat or skip across pages. The sort has no unique tie-breaker. Keep the post ID last in every order.
- Old results appear. A page cache stores the filtered address, or a stale response arrived after a newer one. The abort logic handles the second case, and cache rules handle the first.
- Interactive elements in cards stop working after an update. Bricks scripts initialised at page load do not know about nodes you swapped in. Test cards with sliders, popups or interactions, and prefer the built-in filters if they matter. The Bricks documentation lists custom JavaScript events for its own AJAX features.
- Page two ignores the filter. The pager links drop the parameters, or a Bricks AJAX feature fetches the next page without them. Check the links and test as described in the pagination section.
- Screen reader users hear nothing. The live region was removed or recreated by the swap, or it sits inside the results wrapper. Keep it in the form.
Checklist
- Decide first whether the built-in Bricks Query Filters meet the need, and run only one filtering mechanism on any loop.
- Put every filter value in the query string and render the form and the results from it on the server.
- Prefix all parameter names and avoid WordPress query variables such as s, year, cat, tag, order, orderby and paged.
- Read parameters in one function that checks types, sanitises text, validates dates and allow-lists every fixed choice.
- Cap the search length and the number of topics, and never let the URL set the page size or name a meta key or order column.
- Apply the parameters with bricks/posts/query_vars and guard the callback with the loop’s six character element ID.
- Add the post ID as the last sort key so paging never repeats or skips items.
- Give the results wrapper, summary and pager data attributes through the Style Attributes group so the script can find them.
- Use native controls with visible labels, a fieldset and legend for the chips, and the form as a search landmark.
- Keep one live region with role status in the form, outside the swapped area, fed by the results summary text.
- Set aria-busy on the results while loading, never move focus after a form change, and move it to the results only after a link in them is used.
- Use pushState for discrete changes, replaceState while typing, and restore the controls on popstate.
- Abort an in-flight request before starting another and fall back to a normal page load if a fetch fails.
- Make the pager links and the active filter chips carry the filter parameters, and reset to page one when a filter changes.
- Build an empty state with a clear message, the active filters and a Clear all link.
- Add noindex with follow to filtered URLs and check the response headers and page source for conflicts.
- Test page caching, Bricks AJAX pagination or load more, and interactive cards with filters active.
- Test with the keyboard only, at 200 percent zoom, with a screen reader and with JavaScript disabled.
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 filter a Bricks query loop with URL parameters?
Yes, in two ways. The built-in Query Sort, Filter and Live Search feature reads filter values from URL parameters and keeps browser history, once you enable it in the Bricks settings and add Filter elements. Or you can write your own parameters and apply them to one loop with the bricks/posts/query_vars filter, as this tutorial does. Choose one mechanism per loop, because two systems changing one query will conflict.
Is there a dynamic data tag for URL parameters?
Yes. The Bricks documentation lists a url_parameter tag that returns the value of a parameter in the address. It is useful for showing a value or driving a condition. For filtering a query it is less suitable, because the documented query controls have no way to skip a row when the parameter is missing, whereas PHP can leave the clause out entirely and validate the value first.
Why not name the search parameter s?
WordPress treats s as its own search variable. A request with it can load the search results template instead of your page, and other WordPress query variables such as year, cat, order and paged can change the main query and produce a 404 or the wrong template. A short prefix such as f_ avoids every collision with WordPress and with other plugins.
Do I need to enable code execution in Bricks?
Not for the approach in this tutorial. The query changes live in a plugin or child theme filter, and the form is a shortcode run by the Shortcode element. Code execution is needed for the Query editor control and the Code element when they run PHP, and Bricks also requires a valid code signature for that code. A filter in a plugin avoids both requirements.
How do I find the element ID of my loop?
Each Bricks element has a unique ID. Select the loop element in the builder and look at the HTML ID shown with its classes, which looks like brxe-abc123. The six characters after the prefix are the ID that the bricks/posts/query_vars callback receives. Store it in a constant with a comment, because recreating the element produces a new ID and the filter stops matching.
How do I make the back button work with AJAX filters?
Write every meaningful change to the address with history.pushState, listen for the popstate event, restore the controls from the address, and reload the results without writing history again. While the visitor types, push one entry and replace it afterwards so Back removes the whole search in one step. Ignore popstate events that do not change the address, such as in-page anchor clicks.
How do I announce updated results to screen reader users?
Keep a paragraph with role status in the page before any update, outside the area that is replaced, and set its text to a short message such as the results summary after each update. Mark the results as busy while loading, do not move focus after a form change, and move focus to the results only after a link inside them is activated. WCAG calls these messages status messages.
Should I use fetch with my own code or the Bricks built-in AJAX?
Use the built-in filters when the fields are standard, you want counts, ranges or live search, or cards contain Bricks interactions. Use your own when you need a specific URL shape or logic the elements do not offer, such as a relationship or a computed value. A page fetch like the one here loads a full page each time, while the built-in feature requests only the loop through Bricks, which matters on heavy pages.
Will filtered URLs hurt my SEO?
They can, if every combination is crawlable and indexable, because that creates many thin, overlapping pages. Add noindex with follow to filtered views with the wp_robots filter, keep the unfiltered page indexable, and link to real category archives for topics you want to rank. Check that an SEO plugin does not output a conflicting robots tag, and do not block the same URLs in robots.txt, which would hide the noindex.
Why does page two ignore my filters?
Either the paging links drop the parameters, or a Bricks AJAX feature such as Load more or infinite scroll fetches the next page through a Bricks request that does not carry your address parameters. Hover over a page link with filters active to check the first case, and test the second explicitly. If it fails, use normal paging links or the built-in filter elements, which pass their state with those requests.
Can I filter by a custom field from Meta Box or ACF?
Yes, when the field stores a simple value such as a string, a number or a date in a sortable format, because a meta query compares raw stored values. Fields that store arrays, such as groups or checkbox lists, are serialised and cannot be filtered reliably. Mirror the value you need into a flat meta key on save. The Bricks documentation gives a similar warning for its own filter elements.
Does the filter work without JavaScript?
Yes. The form uses the GET method and points at the page's own address, so submitting it loads the page with the parameters in the query string. The server reads them and renders matching results and a matching form state. The script only makes updates faster. The reset control is a real link and the active filter chips are links that remove one filter each, so they work without scripts as well.



