Sooner or later a page needs content that does not live in its own database: events kept on a partner’s WordPress site, jobs from an applicant system, products from an inventory service, or posts from your own network of sites. Copying that content by hand is brittle, and re-entering it as posts means a sync job someone has to maintain. Reading it live from an API is attractive, and WordPress makes it easy because every WordPress site can expose its content as JSON through the REST API. The difficulty is not getting the data. It is deciding where to fetch it, how long to remember it, what to do when the other side is slow or broken, and how to make sure that whatever comes back cannot hurt your page or your visitors.
The single most important idea in this tutorial is that the visitor’s page should never depend on the other site being up, fast and honest at the moment of the request. Fetching on the server, caching the result, and keeping the last good copy turns a fragile live dependency into a cached copy that refreshes in the background of normal page views. Fetching in the browser can be the right choice, but it hands the work, the failures and the trust problem to every visitor, so it needs a reason.
The tutorial builds one concrete result: a live events list, grouped by month, that reads from a WordPress REST API endpoint. It starts by comparing the three ways to do this in Bricks: the built-in API query loop that the Bricks documentation describes, a server-side PHP function with a transient cache, and client-side JavaScript with fetch. It then looks at what a REST response actually contains, walks through the built-in loop and its limits, and builds the server-side version in four parts: the request with caching and a stale fallback, the parsing and sanitising, the grouping by month, and the rendering with distinct empty, error and stale states. A client-side version follows, with an honest comparison, a decision rule for choosing, a section on CORS, rate limits and secrets, a test plan, and notes on keeping the data fresh.
Some honest boundaries. This is a general guide built from the public Bricks documentation and from the WordPress developer documentation, not a test report, and it contains no benchmark numbers. The built-in API query loop is described by Bricks as experimental, and Bricks changes between versions, so check the current Bricks documentation for the exact controls before you follow any interface steps. The domain names in the examples, such as the events host, are placeholders: the examples use a reserved example domain, and you must replace it with a real endpoint you are allowed to use. Fields such as the event date are an assumption about how your source stores data, so adapt the parsing to your own response.
You will need to be comfortable reading PHP and JavaScript, and to have either a WordPress site whose content you can expose through the REST API, or permission to read another site’s public endpoint. Everything should be tried on a staging copy first. No part of this requires you to turn on PHP execution inside Bricks: the PHP lives in your child theme or a small site plugin, which is where it belongs.
Key points
- A page should never depend on another site being fast and correct at request time; fetch on the server, cache the result and keep the last good copy.
- Bricks offers a built-in API query loop for simple lists, a PHP route with a shortcode or array for grouping and control, and client-side fetch for live interaction.
- Use wp_safe_remote_get, a timeout, a status check and strict JSON handling, and treat every field in the response as untrusted until sanitised.
- Cache with a fresh transient, a longer stale copy and a short failure back-off, and give the page distinct empty, error and stale states.
- Server-side fetching keeps secrets, rate limits and CORS out of the visitor’s browser; fetch client-side only for data that is public, small and interactive.
- Group by month in PHP using the site timezone, escape everything at output, and test the failure paths on purpose before launch.
Three ways to bring outside data into a Bricks page
Bricks gives you more than one route to external data, and each route moves the work to a different place. Choosing well saves rebuilding later. The three routes are the built-in API query loop, a server-side PHP function that you write, and client-side JavaScript that calls the endpoint from the visitor’s browser.
The built-in route is the API query type of the query loop. According to the Bricks documentation, you set the loop’s query type to API, open the API settings, enter a URL and request settings, fetch a preview, choose the part of the response that is an array, and use query_api dynamic data tags inside the loop. Bricks makes the request from the server, can cache the response, and supports paging parameters. It is the fastest way to a working list, and the documentation lists its limits honestly: it is experimental, it has no query filters or live search, it handles only JSON and only array data, it does not retry rate-limited requests, and it offers no schema mapping beyond its tags. That last limit matters for this tutorial: it has no way to group items by month, or to turn a plain date string into a clean heading.
The server-side PHP route is a function you write in a child theme or site plugin. It fetches with wp_safe_remote_get, validates and sanitises the JSON, caches the result in a transient, and hands it to the page in one of two ways: as a shortcode that returns finished HTML, which the Bricks Shortcode element can place, or as an array that an Array query loop iterates. You control timeouts, fallbacks, grouping and escaping. The price is code to maintain.
The client-side route puts a small script on the page that calls the endpoint with fetch and builds the markup in the browser. It suits data that changes while the visitor watches, or that depends on something the visitor does, such as a search box. The price is that the request is made by every visitor’s browser, so it is subject to cross-origin rules, rate limits per visitor, and whatever state the other site is in at that moment, and the content is not in the initial HTML for search engines to read reliably.
Which route to pick is mostly a question of what you need beyond a plain list. The comparison below summarises how they differ; the decision rule later in the tutorial turns it into a procedure. As a starting point: use the built-in loop for a simple list with no grouping and no secrets that need special care; use the PHP route when you need control, grouping, resilience or a custom shape; and use the browser route only for interactive, public, light data.
Three routes to external data
| Built-in API loop | PHP and transient | Browser fetch | |
|---|---|---|---|
| Where the request runs | Your server | Your server | Each visitor browser |
| Setup effort | Settings in the builder | A function in code | A script and markup |
| Grouping and reshaping | Not offered | Full control in PHP | Full control in JavaScript |
| Failure handling | Limited and documented | Yours: stale copy, back-off | Yours: shown per visitor |
| Secrets | PHP constants supported | Stay on the server | Cannot be hidden |
| Search engines | In the HTML | In the HTML | Added after load |
The WordPress REST API in practice: what an events endpoint returns
Every WordPress site exposes a REST API under a path that normally looks like /wp-json/wp/v2/ followed by a resource name. Posts are at posts, pages at pages, and any custom post type registered with REST support gets its own route. If the site does not use pretty permalinks, the same API is reachable through a query string route; check the WordPress developer documentation for the exact form. A GET request on a collection returns a JSON array of objects, which is exactly the shape that a loop wants.
A few conventions of the core API matter for what follows. The per_page parameter controls how many items you get, with a maximum of one hundred. The _fields parameter trims each object to the properties you name, which can shrink a response dramatically, and you should always use it for lists. The response headers X-WP-Total and X-WP-TotalPages report how many items and pages exist, which is how paging works. Rendered fields such as the title arrive inside an object with a rendered key, and they are HTML, not plain text: a title with an ampersand or a typographic dash arrives with HTML entities in it. And custom fields appear under meta only if they were registered for REST and the post type supports custom fields.
The source site for the events example must therefore do two things: register an events post type with REST support, and register the event date as meta that is exposed. The code below is for the source site, shown so that you know what shape the data will have; if you are reading someone else’s site, you only need to look at what their endpoint returns.
add_action( 'init', function () {
register_post_type( 'event', array(
'label' => 'Events',
'public' => true,
'show_in_rest' => true,
'rest_base' => 'events',
'supports' => array( 'title', 'editor', 'custom-fields' ),
) );
register_post_meta( 'event', 'event_date', array(
'type' => 'string',
'single' => true,
'show_in_rest' => true,
'sanitize_callback' => 'sanitize_text_field',
) );
register_post_meta( 'event', 'event_city', array(
'type' => 'string',
'single' => true,
'show_in_rest' => true,
'sanitize_callback' => 'sanitize_text_field',
) );
} );
The post type is public, exposed to REST under the base name events, and declares support for custom fields, which is what allows meta to appear in responses. The two register_post_meta calls expose a date and a city as single string values. With that in place, a request for the collection with a trimmed field list looks like this, and returns an array like the second block:
https://events.example.com/wp-json/wp/v2/events?per_page=50&_fields=id,title,link,meta
[
{
"id": 412,
"link": "https://events.example.com/events/spring-meetup/",
"title": { "rendered": "Spring meetup & workshop" },
"meta": { "event_date": "2027-03-14", "event_city": "Lisbon" }
},
{
"id": 398,
"link": "https://events.example.com/events/summer-camp/",
"title": { "rendered": "Summer camp" },
"meta": { "event_date": "2027-06-02", "event_city": "Porto" }
}
]
Notice what the response does not give you: it is not sorted by the meta date, it contains events that may already be in the past, and the title contains an entity. Sorting by a custom field through the API needs extra server-side work on the source site, so the examples here sort in PHP on your side. Notice also that the date is a plain string in a fixed format. That is a gift: a date with no time and no timezone is the least ambiguous thing an API can send, provided you parse it with a strict format and do not let a timezone creep in.
Option A: the built-in API query loop, step by step and where it stops
If your list is simple, the built-in API query loop may be all you need, and it is worth trying first because it requires no code. The Bricks documentation describes the workflow, and the steps below follow it; because the feature is marked experimental, confirm the details in the current documentation.
Add a supported layout element such as a Container, Block or Div, enable the query loop on it, and set the query type to API. Open the API settings. The URL is required and must return JSON; you can add a name as an internal label, choose GET (the right choice for reading) or POST, and add headers and URL parameters. For the events endpoint you would enter the collection URL and add parameters such as per_page and _fields. Dynamic data is supported in most string settings, so a URL parameter can depend on the current page, though the name and the response path are not parsed. Use the fetch button in the preview panel to see the response tree, and set the response path to the part that is the array: leave it empty when the top level is already an array, as with a WordPress collection, or use dot notation such as data.results for nested data.
Inside the loop, read fields with the API tag: {query_api @key:'link'} for a top-level key, and a pipe to reach into nested keys, as in {query_api @key:'title|rendered'} for the rendered title, or {query_api @key:'meta|event_date'} for the date. The preview lets you hover a field to copy a ready-made tag. Add elements for the title, date and city inside the loop, link the title to the item’s link, and you have a working, ungrouped list rendered on the server.
Several details of the documented behavior help you avoid surprises. Responses are cached with transients when the cache duration is above zero, and the default duration is three hundred seconds, so a change on the source takes up to five minutes to appear, and a longer duration suits slow or rate-limited sources. The cache key includes the endpoint, method, headers, parameters and body, so different requests do not collide. Clicking fetch in the settings clears that element’s cache, which helps while you debug. For authorization, Bricks supports an API key, a bearer token and basic authentication; for anything sensitive, enable the option that reads the secret from a PHP constant rather than storing it in the builder, where exports, screenshots and team access can expose it. The constant names are built from the loop element’s ID in uppercase, and you define them in wp-config.php.
Pagination is possible when the API accepts page or offset parameters and reports a total. For the WordPress REST API the documented setup uses a page parameter named page, a per-page parameter of per_page, and a total path that reads the X-WP-TotalPages header. Bricks also offers filters for the request: you can change the request arguments, such as the timeout, the headers and the body, in PHP, and an action runs after the response so you can log failures.
Now the limits, because they decide whether this route is enough. The loop renders items in the order the API returns them, and there is no built-in way to drop past events, sort by a field inside the loop, or insert a month heading between groups. API loops do not support query filters or live search, and there is no automatic retry or back-off when the source rate-limits you. If a request fails, you see the failure states Bricks documents rather than a stale copy of the last good data. For the live events list in this tutorial, those gaps are exactly the requirements, which is why the next sections build the server-side version. For a “latest posts from our other site” strip, though, the built-in loop is a perfectly good answer.

Option B: fetch on the server and cache, with a safety net
The server-side function has one job: return the events, quickly and safely, no matter what state the source site is in. It achieves that with three stored copies and a few rules. A fresh copy lasts fifteen minutes and is what normal requests read. A stale copy lasts a day and is the fallback when the source fails. A short failure marker lasts five minutes and tells the function not to hammer a source that just failed. The request path in the figure below shows the order of decisions: serve fresh if you have it, otherwise respect the failure marker, otherwise fetch, otherwise fall back to stale.
Put this in your child theme’s functions.php or a small site plugin. Replace the host, and treat the function and transient names as examples; prefixing everything with your own short prefix avoids collisions.
function wpr_events_endpoint( $per_page ) {
return add_query_arg(
array(
'per_page' => $per_page,
'_fields' => 'id,title,link,meta',
),
'https://events.example.com/wp-json/wp/v2/events'
);
}
function wpr_get_events( $per_page = 50 ) {
$per_page = max( 1, min( 100, absint( $per_page ) ) );
$fresh_key = 'wpr_events_fresh_' . $per_page;
$stale_key = 'wpr_events_stale_' . $per_page;
$wait_key = 'wpr_events_wait';
$fresh = get_transient( $fresh_key );
if ( is_array( $fresh ) ) {
return $fresh;
}
$stale = get_transient( $stale_key );
$stale = is_array( $stale ) ? $stale : null;
if ( get_transient( $wait_key ) ) {
return $stale;
}
$response = wp_safe_remote_get(
wpr_events_endpoint( $per_page ),
array(
'timeout' => 5,
'redirection' => 2,
'headers' => array( 'Accept' => 'application/json' ),
)
);
$events = wpr_parse_events_response( $response );
if ( null === $events ) {
set_transient( $wait_key, 1, 5 * MINUTE_IN_SECONDS );
return $stale;
}
set_transient( $fresh_key, $events, 15 * MINUTE_IN_SECONDS );
set_transient( $stale_key, $events, DAY_IN_SECONDS );
return $events;
}
Read it from the top. The endpoint builder uses add_query_arg, which encodes the parameters, and always requests a trimmed field list. The main function clamps the page size to the REST maximum with absint, then builds three transient keys that include the size, so different list lengths never share a cache. If a fresh copy exists, it is returned immediately. is_array is the right test because an empty array is a legitimate cached answer, “no events”, and must not trigger a refetch on every request. If there is no fresh copy, it loads the stale copy, or null when there is none, and checks the failure marker: during the back-off window it returns the stale copy without calling the source at all.
The request itself uses wp_safe_remote_get rather than wp_remote_get. The safe variant rejects URLs that point at local or private addresses, which closes off a class of server-side request forgery problems if the URL ever becomes configurable. The timeout of five seconds bounds how long a visitor can be stuck behind a slow source, and the redirect limit stops redirect chains. The parser, shown next, returns null on any failure, and that is the signal to set the failure marker and fall back. On success both the fresh and the stale copies are written.
The return values form a small contract the rest of the code relies on. An array, possibly empty, means “here is the data”. Null means “no data at all”: the source failed and there is no stale copy. That distinction is what lets the page say “no upcoming events” in one case and “events are unavailable” in the other, instead of showing the same blank for both.
Request path for the server-side events list
- Page render asks for eventsThe shortcode or array function calls wpr_get_events.
- Fresh copy?A fifteen-minute transient; if present, return it at once.
- Recent failure?A five-minute marker; if set, skip the request and use stale data.
- Fetch with a timeoutwp_safe_remote_get, five seconds, limited redirects.
- Validate and sanitiseStatus 200, valid JSON, clean fields; null on any problem.
- Store or fall backSuccess writes fresh and stale copies; failure sets the marker and serves stale.
Turn the JSON into clean data: validate, sanitise, sort
The response is data from outside your system, and it deserves the same suspicion as a form submission. The parser has three jobs: decide whether the response is usable at all, extract only the fields you need, and make each of them safe and strict. It also decides what to do with a single bad item: skip it, and keep the rest, so that one malformed event does not blank the whole list.
function wpr_parse_events_response( $response ) {
if ( is_wp_error( $response ) ) {
return null;
}
if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
return null;
}
$data = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $data ) ) {
return null;
}
$events = array();
foreach ( $data as $item ) {
if ( ! is_array( $item ) ) {
continue;
}
$title = isset( $item['title']['rendered'] ) && is_string( $item['title']['rendered'] ) ? $item['title']['rendered'] : '';
$title = trim( html_entity_decode( wp_strip_all_tags( $title ), ENT_QUOTES, 'UTF-8' ) );
$date = isset( $item['meta']['event_date'] ) && is_string( $item['meta']['event_date'] ) ? $item['meta']['event_date'] : '';
$day = DateTimeImmutable::createFromFormat( '!Y-m-d', $date, wp_timezone() );
$link = isset( $item['link'] ) && is_string( $item['link'] ) ? esc_url_raw( $item['link'], array( 'https' ) ) : '';
$city = isset( $item['meta']['event_city'] ) && is_string( $item['meta']['event_city'] ) ? sanitize_text_field( $item['meta']['event_city'] ) : '';
if ( '' === $title || '' === $link || ! $day || $day->format( 'Y-m-d' ) !== $date ) {
continue;
}
$events[] = array(
'title' => sanitize_text_field( $title ),
'date' => $date,
'city' => $city,
'url' => $link,
);
}
usort( $events, function ( $a, $b ) {
$by_date = strcmp( $a['date'], $b['date'] );
return 0 !== $by_date ? $by_date : strcmp( $a['title'], $b['title'] );
} );
return $events;
}
Going through the checks in order. A WP_Error means the request itself failed, for example a timeout or a blocked URL; anything other than status 200 means the source answered but not with data, which includes rate-limit and server-error responses; and a body that does not decode to an array means the source sent something else, perhaps an HTML error page from a proxy. Each returns null, the failure signal. Decoding with the associative flag gives arrays rather than objects, and every field access afterwards is guarded with isset and a type check, because a source that changes shape should cause skipped items, not fatal errors or notices.
The title arrives as rendered HTML, so the code strips tags and then decodes entities, producing plain text; the text is stored as text and escaped later when it is printed. The date is parsed with a strict format, with an exclamation mark at the start so the time resets to midnight in the site’s timezone, and then compared with its own re-formatted value. That comparison catches impossible dates such as the thirty-first of February, which PHP would otherwise quietly roll into March. The link must be a valid address using the secure scheme, or it becomes empty. Any item missing a title, link or valid date is skipped. The city is optional text.
Finally the list is sorted by date and then title. The sort uses plain string comparison, which is correct for dates in year-month-day format. Sorting here, once, before caching, means the page code never has to sort, and the cached copy is already in display order. An empty source response yields an empty array, a valid result meaning there are no events. Keep the parser the only place that knows the source’s field names. If the source changes, you change one function, and the rest of the pipeline sees the same clean shape of title, date, city and URL.

Group by month and put the list on the page
With clean, sorted data, grouping is a small loop. The function below drops events that have already happened, applies a limit, and builds one group per calendar month. It does its date work in the site’s timezone, so an event on the first of the month appears under that month for your visitors, whatever the server’s clock says.
function wpr_events_grouped( $limit = 20 ) {
$events = wpr_get_events();
if ( null === $events ) {
return null;
}
$limit = max( 1, min( 50, absint( $limit ) ) );
$today = new DateTimeImmutable( 'today', wp_timezone() );
$groups = array();
$count = 0;
foreach ( $events as $event ) {
$day = DateTimeImmutable::createFromFormat( '!Y-m-d', $event['date'], wp_timezone() );
if ( ! $day || $day < $today ) {
continue;
}
if ( $count >= $limit ) {
break;
}
$key = $day->format( 'Y-m' );
if ( ! isset( $groups[ $key ] ) ) {
$groups[ $key ] = array(
'label' => wp_date( 'F Y', $day->getTimestamp() ),
'events' => array(),
);
}
$groups[ $key ]['events'][] = array(
'title' => $event['title'],
'date' => $event['date'],
'day' => wp_date( 'j M', $day->getTimestamp() ),
'city' => $event['city'],
'url' => $event['url'],
);
$count++;
}
return array_values( $groups );
}
The function passes a null through, so the caller can show the error state. Otherwise it computes midnight today in the site timezone and skips earlier events. Because the input is already sorted, groups are created in chronological order, and the loop stops at the limit. The group label comes from wp_date, which formats in the site’s timezone and language, so month names follow the site locale. Each event carries a short display day as well as the machine-readable date, which the markup uses in a time element.
There are two ways to put this on a Bricks page. The first returns finished HTML through a shortcode, which the Bricks Shortcode element can place by typing the shortcode with its square brackets into the element; the element also has an option to show a placeholder in the builder instead of rendering the shortcode, which is useful when a remote call would slow the editor. The second hands the groups to an Array query loop, so that designers control the markup in the builder. The shortcode needs no code execution setting in Bricks; the array route uses the echo tag and therefore needs code execution and an allow-listed function name, as explained in the PHP query tutorial.
add_shortcode( 'wpr_events', function ( $atts ) {
$atts = shortcode_atts( array( 'limit' => 20 ), $atts, 'wpr_events' );
$groups = wpr_events_grouped( $atts['limit'] );
if ( null === $groups ) {
return '<p class="wpr-events__notice">The events list is unavailable right now. Please try again later.</p>';
}
if ( ! $groups ) {
return '<p class="wpr-events__notice">No upcoming events at the moment. Check back soon.</p>';
}
$html = '<div class="wpr-events">';
foreach ( $groups as $group ) {
$html .= '<section class="wpr-events__month">';
$html .= '<h3 class="wpr-events__heading">' . esc_html( $group['label'] ) . '</h3>';
$html .= '<ul class="wpr-events__list">';
foreach ( $group['events'] as $event ) {
$html .= '<li class="wpr-events__item">';
$html .= '<time datetime="' . esc_attr( $event['date'] ) . '">' . esc_html( $event['day'] ) . '</time> ';
$html .= '<a href="' . esc_url( $event['url'] ) . '">' . esc_html( $event['title'] ) . '</a>';
if ( '' !== $event['city'] ) {
$html .= ' <span class="wpr-events__city">' . esc_html( $event['city'] ) . '</span>';
}
$html .= '</li>';
}
$html .= '</ul></section>';
}
return $html . '</div>';
} );
The shortcode accepts a limit attribute, so you write [wpr_events limit="12"] in the Shortcode element. It returns one of three things: an unavailable notice for null, an empty-state notice for an empty list, or the list. Every value that reaches the markup is escaped for its context: esc_html for text, esc_attr for the datetime attribute, esc_url for the link. The data was sanitised on the way in and is escaped on the way out, which is the pattern to keep. Adjust the heading level to fit the page outline. For the array route, a thin wrapper that returns wpr_events_grouped() serves an outer Array loop whose items have a label and a nested events list, and the Bricks documentation describes nesting a second Array loop whose source is the inner key.

Empty, error and stale states: designing for the other side failing
A list that works when everything is fine is half a feature. The other half is what visitors see when the source returns nothing, returns garbage, or does not answer. Four situations need different treatment, and conflating them is the most common design mistake with external data.
An empty list is not an error. The source answered correctly and there are simply no upcoming events. The page should say so in friendly words and, ideally, offer something to do: a link to subscribe, a contact address or a link to past events. In the shortcode above this is the case where the grouped array is empty. Treating it as an error would alarm visitors and send you looking for a fault that does not exist.
An error with no fallback data is a different matter: the function returned null, because the source failed and there is no stale copy. Here the honest message is that the list is unavailable, with a static link to the source site’s own events page so the visitor still has a path forward. Do not render a half-empty list or an error code from the other site. Log the failure for yourself, but with care: a failing source can generate a flood of identical log lines, so log once per back-off window, which the failure marker makes easy.
A stale copy is the quiet success of this design. When the source is down but a copy from earlier today exists, the function returns it, and visitors see a list that may be slightly old rather than nothing. For a list of events that is almost always the right trade. If freshness matters more, store a timestamp alongside the data and show “last updated” text, or refuse to serve data older than a limit you choose. Decide on purpose; do not leave it to whatever the cache happens to hold.
The loading state exists only in the client-side route, since the server renders only after it has an answer. There, show a placeholder of the right height so the layout does not jump, mark the container as busy for assistive technology while the request runs, and replace the placeholder when it finishes. A skeleton of the final shape is kinder than a spinner, and respects visitors who have asked for reduced motion if you avoid animating it.
One interaction deserves a warning. If a page cache stores the finished HTML, it also stores the error message when the page happened to be built during an outage. Visitors then keep seeing “unavailable” until the page cache entry expires, even though your transient recovered minutes ago. There are three ways to handle it. Keep the page cache lifetime for pages with external data short. Exclude the list’s page from caching if the source is unreliable. Or render the error state with a small client-side refresh script that retries once. Whichever you choose, include the page cache in your test plan, and remember that the freshness of the list is never better than the longest cache in front of it. Accessibility applies to states as well: notices are real text, never color alone, and live updates use a polite live region.


Option C: the same list fetched in the browser
The client-side version fetches the endpoint from the visitor’s browser and builds the list with the DOM. It is worth writing carefully because the browser is the least trustworthy place to handle remote data: it must not treat the response as HTML, it must not trust links, and it must not hang forever.
In the builder, add a Div, give it a class such as wpr-events, and add custom attributes under the Style tab’s Attributes group: data-events-endpoint with the full endpoint address, data-events-limit with a number, and aria-live with the value polite. Put a plain fallback inside the Div, such as a sentence with a link to the source’s calendar; the script replaces it. Then load the script on this page only, using the techniques from the custom CSS and JavaScript tutorial, such as a body footer script in the page settings or a conditionally enqueued file.
(function () {
var roots = document.querySelectorAll('[data-events-endpoint]');
if (!roots.length) { return; }
var ALLOWED_HOSTS = ['events.example.com'];
function plainText(html) {
return new DOMParser().parseFromString(String(html || ''), 'text/html').body.textContent.trim();
}
function parseDay(value) {
var m = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(String(value || ''));
if (!m) { return null; }
var day = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
return day.getMonth() === Number(m[2]) - 1 ? day : null;
}
function safeUrl(value) {
try {
var u = new URL(String(value || ''));
return u.protocol === 'https:' ? u.href : '';
} catch (e) {
return '';
}
}
function iso(d) {
var mm = String(d.getMonth() + 1).padStart(2, '0');
var dd = String(d.getDate()).padStart(2, '0');
return d.getFullYear() + '-' + mm + '-' + dd;
}
function toEvents(data) {
if (!Array.isArray(data)) { throw new Error('Unexpected response'); }
var today = new Date();
today.setHours(0, 0, 0, 0);
return data.map(function (item) {
var meta = (item && item.meta) || {};
return {
title: plainText(item && item.title && item.title.rendered),
day: parseDay(meta.event_date),
city: plainText(meta.event_city),
url: safeUrl(item && item.link)
};
}).filter(function (e) {
return e.title && e.url && e.day && e.day >= today;
}).sort(function (a, b) {
return a.day - b.day;
});
}
function notice(root, text) {
var p = document.createElement('p');
p.textContent = text;
root.textContent = '';
root.appendChild(p);
}
function render(root, events, limit) {
if (!events.length) { notice(root, 'No upcoming events at the moment. Check back soon.'); return; }
var monthFmt = new Intl.DateTimeFormat(undefined, { month: 'long', year: 'numeric' });
var dayFmt = new Intl.DateTimeFormat(undefined, { day: 'numeric', month: 'short' });
var frag = document.createDocumentFragment();
var currentKey = '';
var list = null;
events.slice(0, limit).forEach(function (e) {
var key = e.day.getFullYear() + '-' + e.day.getMonth();
if (key !== currentKey) {
currentKey = key;
var h = document.createElement('h3');
h.textContent = monthFmt.format(e.day);
list = document.createElement('ul');
frag.appendChild(h);
frag.appendChild(list);
}
var li = document.createElement('li');
var time = document.createElement('time');
time.setAttribute('datetime', iso(e.day));
time.textContent = dayFmt.format(e.day) + ' ';
var a = document.createElement('a');
a.href = e.url;
a.textContent = e.title;
li.appendChild(time);
li.appendChild(a);
if (e.city) {
var span = document.createElement('span');
span.textContent = ' ' + e.city;
li.appendChild(span);
}
list.appendChild(li);
});
root.textContent = '';
root.appendChild(frag);
}
function load(root) {
var url;
try { url = new URL(root.getAttribute('data-events-endpoint') || ''); } catch (e) { return; }
if (url.protocol !== 'https:' || ALLOWED_HOSTS.indexOf(url.hostname) === -1) { return; }
var limit = parseInt(root.getAttribute('data-events-limit'), 10) || 20;
var controller = new AbortController();
var timer = window.setTimeout(function () { controller.abort(); }, 8000);
root.setAttribute('aria-busy', 'true');
fetch(url.href, { headers: { Accept: 'application/json' }, credentials: 'omit', signal: controller.signal })
.then(function (res) {
if (!res.ok) { throw new Error('HTTP ' + res.status); }
return res.json();
})
.then(function (data) { render(root, toEvents(data), limit); })
.catch(function () { notice(root, 'The events list is unavailable right now. Please try again later.'); })
.then(function () {
window.clearTimeout(timer);
root.removeAttribute('aria-busy');
});
}
roots.forEach(load);
})();
The script finds containers by attribute, so it exits at once on pages without one. It checks the endpoint twice: the address must parse, use the secure scheme and match an allow-listed host, so an attribute cannot point the script somewhere unintended. plainText parses the rendered title with DOMParser, which builds an inert document that never runs scripts, and reads its text, which both decodes entities and strips tags. Every value is later placed with textContent or a checked URL, never with innerHTML, so a hostile title is displayed as text instead of running. Dates are parsed from their parts into local time instead of passing the string to the Date constructor, which would read a plain date as UTC and could shift it a day. The request omits credentials, has no custom headers beyond a safelisted Accept header, and aborts after eight seconds. Avoiding an Authorization header or a JSON content type also avoids a cross-origin preflight request, which the source might not answer.
Server or client? A decision rule
The two routes are not equals, and the right default is the server. Three properties make the case, and they apply to nearly every list of external content.
First, search engines and the first paint. Server-rendered content is in the HTML the browser and crawlers receive. Content added by JavaScript after load may be indexed later or not at all, and the visitor sees an empty area, then a flash of content. Second, resilience. With the server route one cached copy serves everyone, the source sees one request every fifteen minutes, and an outage is absorbed by the stale copy. With the browser route every visitor makes their own request, the source sees them all, and every visitor experiences the outage themselves. Third, trust. On the server you decide what the data is allowed to do before it reaches the page. In the browser you can still sanitise, as the script above does, but secrets cannot be hidden and the logic is visible to everyone.
The browser route earns its place when the data must respond to the visitor: a search box over a public catalogue, a filter that fetches matching items, a live count. The data should be public, small and safe to expose, the endpoint should send the right cross-origin headers, and the page should work acceptably without it. A hybrid is often best: render the initial list on the server for speed, search engines and resilience, and let a small script fetch more or filter after interaction. That also gives you a natural no-script fallback.
Within the server route, the built-in API query loop versus your own function is a smaller choice. Use the built-in loop for plain, ordered lists with moderate needs, and accept its limits: no grouping, no query filters, no retry. Choose your own function when you need grouping or reshaping, a stale fallback, strict validation or custom caching. If you later need faceted filtering across the external items, neither route does it well; the Bricks documentation itself suggests syncing the external data into WordPress, as posts or terms, when you need filtering, searching, sorting or complex joins.
The figure condenses this into questions to ask in order. Notice that most branches end on the server. A client-side fetch should have a reason you can state in one sentence, such as “the list must update as the visitor types.” If the sentence is “it was easier to paste a script”, reconsider.
Where should the request run?
CORS, rate limits and secrets: why the server is the safer place
Three kinds of friction explain most of the advice above, and they are worth understanding rather than memorising.
CORS, cross-origin resource sharing, is a browser rule. By default a script on one origin cannot read the response of a request to another origin, unless the other server explicitly allows it with response headers. It protects the visitor, not the source. A request from your server is not a browser request and is not subject to it, which is why the Bricks API query documentation says to check CORS only when custom front-end scripts call the API directly, since the built-in requests are made through WordPress. For the client-side route, the practical consequences are: the source must send an allow header that matches your origin; a request with custom headers or non-simple content types triggers a preflight request that the source must also answer; and security plugins, firewalls and CDNs on the source side can add, strip or block those headers. WordPress core handles cross-origin requests to its REST API in its own way by default, but hosts and plugins often change it, so test from a real page on your real domain. A non-WordPress API frequently sends no cross-origin headers at all, and then only the server route works.
Rate limits are the second friction. Sources limit how often a client may call, usually by address. When your server fetches, all your visitors share one address and one cache, so one request per cache lifetime is trivial. When browsers fetch, each visitor counts against the limit separately, and a traffic spike can get your visitors blocked at the source. Server-side code should also respect a refusal: treat status 429 and server errors as failures, honor a retry-after header if you read it, and use the failure marker to back off, as the function in this tutorial does. The built-in Bricks loop has no automatic retry or back-off, according to its documentation, which matters if your source is strict.
Secrets are the third. Anything delivered to a browser is public: keys in script files, in data attributes, in inline settings or in the page source. If an API needs credentials, the request must be made on the server. For the built-in loop, Bricks documents reading credentials from PHP constants named after the loop’s element ID, rather than storing them in the builder. For your own function, define a constant in wp-config.php and send it in a header from PHP; never echo it into the page and never log it. If the source is another WordPress site that needs authentication, a dedicated low-privilege user with an application password, a core WordPress feature, is better than sharing a real account, and the password should be revocable and used read-only.
Two more security points apply to the whole topic. Never build the request address from visitor input; if the endpoint must vary, choose from a short list you control, and keep using the safe request function that refuses private addresses. And remember the data itself is untrusted: sanitise on the way in, escape on the way out, and render with text-only methods in the browser. Finally, think about permission and privacy. Check that the source’s terms allow you to republish its content, and note that a browser fetch discloses each visitor’s address to the third party, which can matter under privacy rules. This is general orientation, not legal advice; ask a qualified professional when the data is personal or commercial.
Test it, then fix what goes wrong
External data fails in ways your own content never does, so test the failure paths deliberately, on a staging copy, before launch. WordPress makes outages easy to simulate: the HTTP API passes every request through a filter that can short-circuit it. Add this temporarily on staging, and remove it afterwards.
add_filter( 'pre_http_request', function ( $pre, $args, $url ) {
if ( false !== strpos( $url, 'events.example.com' ) ) {
return new WP_Error( 'wpr_test', 'Simulated outage' );
}
return $pre;
}, 10, 3 );
When the filter returns a WP_Error for the events host, the request never leaves your server and the function sees a failed response, exactly as in a real outage. Use it to prove each state in turn. With an empty cache and the outage on, the page should show the unavailable notice. With a stale copy present, it should show the old list. Delete the fresh transient with wp transient delete wpr_events_fresh_50 to force the fallback path, and delete the failure marker with wp transient delete wpr_events_wait to test the retry. Return a short array with a 429 status in the same filter to see rate-limit handling. Then test the data: add events on the source with a title containing an ampersand, a title containing an HTML tag, a missing date, an impossible date and a past date, and confirm that each is handled as designed, with the tag displayed as text and never executed.
Two environmental tests catch the subtle bugs. Set the site’s timezone far from your server’s, and create an event on the first day of a month, to confirm the grouping follows the site timezone. And turn on the page cache, load the page during a simulated outage, then end the outage and see how long the error notice lingers; that number is your real freshness, and it is set by the page cache, not by your transient. For the browser version, use the developer tools to go offline, to throttle the network, and to read the console for cross-origin errors, and load the page with JavaScript disabled to see the fallback text.
When something is wrong, these are the usual causes. The list is empty but the endpoint shows data: the parser skipped every item, most often because the date is missing from the response. If the source post type does not declare custom field support, or the meta is not registered for REST, the meta object is empty and every event fails validation. Count skipped items and log the number once so this is visible. The request works in a browser or command line but fails from WordPress: the safe request function rejected the address, the server’s certificate store is outdated, or the source blocks your host’s address. The error message inside the WP_Error says which; log it.
Dates are a day off: either the date string was parsed as UTC, or the server timezone was used instead of the site timezone. Titles show codes such as an ampersand entity: rendered HTML was not decoded. The list never updates: look at every cache in front, the page cache first, then your transient, the Bricks cache duration if you use the built-in loop, and any object cache. Events beyond the first hundred are missing: the REST API caps a page at one hundred items, so a larger source needs paging driven by the total pages header, with a sensible upper bound on the number of pages you will fetch. The browser version fails only on some sites: read the console for a cross-origin message and fix it on the source, or move the request to the server.
A test order for the events list
Keep it fresh without making visitors pay
Caching has two numbers to choose, how long data may be old and who pays when it expires, and the defaults in the function above, fifteen minutes fresh and a day stale, are examples to tune. Choose the fresh lifetime from how often the source really changes and how much staleness your visitors would notice. An events list that changes a few times a week gains nothing from a one-minute lifetime, while a stock count might. Choose the stale lifetime from how long you would rather show old data than none; for events that is days. A longer fresh lifetime also lowers the load on the source, which is polite when it is someone else’s server.
Who pays on expiry is the other half. With the function as written, the first visitor after the fresh copy expires waits for the request, up to the five second timeout. On a quiet site that is fine. On a busy site, many visitors can arrive during the same refresh and each start their own request, a stampede. The cleaner design is to let a scheduled task refresh the data, so visitors only ever read caches. WordPress has a scheduler built in:
add_action( 'wpr_refresh_events', function () {
delete_transient( 'wpr_events_fresh_50' );
delete_transient( 'wpr_events_wait' );
wpr_get_events( 50 );
} );
add_action( 'init', function () {
if ( ! wp_next_scheduled( 'wpr_refresh_events' ) ) {
wp_schedule_event( time() + MINUTE_IN_SECONDS, 'hourly', 'wpr_refresh_events' );
}
} );
The first block defines the task: it deletes the fresh copy and the failure marker, then calls the normal function, which fetches and stores new copies. If the fetch fails, the stale copy is still there for visitors. The second block schedules the task hourly if it is not already scheduled. Because the schedule is hourly and the fresh lifetime is fifteen minutes, visitors can still trigger a refresh between runs; lengthen the fresh lifetime to match the schedule if you want visitors never to wait, or accept the hybrid. In a plugin, clear the scheduled hook on deactivation. WordPress runs scheduled tasks when someone visits the site, so a very quiet site may run them late; many hosts let you replace that trigger with a real server cron job that calls the cron entry point, which is more reliable.
Keep the payload small, since it is cached and re-parsed. Always request the trimmed field list, ask for only as many items as you will show, and never cache the full source response if you only need a few fields. Store the cleaned array, not the raw JSON, so each page view does no parsing. The WordPress HTTP API asks for compressed responses on its own, so there is nothing to configure there.
Think about manual control too. An editor who has just fixed a typo on the source will want the list updated now. A WP-CLI command to delete the fresh transient is one answer, and for non-technical editors a small admin action that does the same, protected by a capability check and a nonce, is better than telling them to wait. If the source can notify you with a webhook when content changes, a protected endpoint on your site that clears the fresh copy gives near real-time freshness with the cache’s cost. Whatever you add, keep the rule from earlier: events that change data are triggered by an editorial or scheduled action, never directly by an anonymous page view.
Checklist
- Decide the route first: built-in API query loop for simple ordered lists, a server-side PHP function for grouping and resilience, browser fetch only for visitor-driven updates on public data.
- Use the REST API’s _fields and per_page parameters so the response contains only the fields you need, and remember that one page holds at most one hundred items.
- Make requests with wp_safe_remote_get, a short timeout and a redirect limit, and never build the address from visitor input.
- Treat anything other than status 200 and a valid JSON array as a failure, and skip a bad item instead of failing the whole list.
- Sanitise every field on the way in (strip tags, decode entities, strict date parsing, https-only URLs) and escape on the way out with esc_html, esc_attr and esc_url.
- Cache a fresh copy, a longer stale copy and a short failure marker, and use is_array so an empty list is a valid cached answer.
- Distinguish three states in the page: data, empty (no events) and unavailable (no data at all), each with its own message and a useful next step.
- Parse and group dates in the site timezone, with a strict date format, and drop events that have already passed.
- Keep secrets in PHP constants, never in scripts, data attributes, Bricks settings that are exported or the page source.
- If you use the built-in API loop, set the response path to the array, choose a cache duration that suits the source and use the PHP constant option for credentials.
- For client-side fetch, allow-list the endpoint host, set a timeout with AbortController, send no credentials, and render with textContent instead of innerHTML.
- Check cross-origin behavior from a real page on your real domain before relying on browser fetch, and avoid custom headers that trigger preflight requests.
- Give the browser route a server-rendered or static fallback so the page still works without JavaScript or when the request fails.
- Test the outage paths with the pre_http_request filter on staging, including an empty cache, a stale copy, a 429 response and hostile titles.
- Measure real freshness with the page cache on, since an error page can be cached longer than your transient lives.
- Refresh with a scheduled task where traffic is high, log failures once per back-off window, and confirm you are allowed to republish the source content.
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 Bricks show content from another WordPress site's REST API?
Yes. The Bricks documentation describes an API query loop that fetches JSON from a URL, including a WordPress REST endpoint such as the posts collection, and renders each array item with API dynamic data tags. It is documented as experimental, so check the current Bricks documentation. For grouping, sorting or fallbacks, a PHP function that fetches, caches and outputs the list gives you more control than the built-in loop.
What is the difference between the built-in API loop and my own PHP function?
The built-in loop is configured in the builder and handles the request, a transient cache and simple paging, but it renders items in API order and cannot group by month, drop past items or serve a stale copy when the source fails. A PHP function does all of that, at the cost of code to maintain. Use the built-in loop for plain lists, and write a function when you need control or resilience.
Is it better to fetch on the server or in the browser?
Server side is the better default. The content is in the HTML for search engines, one cached copy serves every visitor, secrets stay hidden, and an outage can be absorbed by a stale copy. Browser fetch suits visitor-driven updates on public, light data, such as search as you type. It exposes every visitor to the source's failures and rate limits, and it needs correct cross-origin headers from the source.
Why does my browser fetch fail with a CORS error?
The browser blocks scripts from reading a cross-origin response unless the source sends headers allowing your origin. WordPress handles cross-origin REST requests in its own way by default, but hosts, firewalls and plugins can change it, and many non-WordPress APIs send nothing. Fix it on the source, avoid custom headers that trigger a preflight request, or move the request to the server, where CORS does not apply.
How do I keep an API key out of the browser?
Make the request on the server and keep the key in a PHP constant defined in wp-config.php, sent in a header from PHP, never printed into the page and never logged. For the built-in API loop, Bricks documents an option to read credentials from PHP constants named after the loop's element ID, instead of storing them in the builder where exports and screenshots can reveal them. Anything delivered to a browser is public.
How long should I cache the data?
Choose the fresh lifetime from how often the source changes and how much staleness visitors would notice; fifteen minutes is a reasonable starting example for a list that changes a few times a week. Keep a longer stale copy as a fallback, for example a day, and a short failure marker of a few minutes. Remember that a page cache in front of the page can make the real freshness longer than your transient.
What should the page show when the API is down?
Show the last good copy if you have one. If you have none, show a clear unavailable notice with a link to the source's own page, not a blank area or a raw error. Keep this separate from the empty state, where the source answered correctly and there are simply no events. Log the failure once per back-off window instead of on every request, and test both paths deliberately.
Why are my event dates a day off?
A plain date string passed to the browser's Date constructor is read as UTC, which can shift it back a day in time zones west of UTC. On the server the cause is usually parsing with the server timezone instead of the site's. Parse the year, month and day parts yourself in the browser, and in PHP use a strict format with wp_timezone, then compare the result with the input to reject impossible dates.
Is it safe to print titles from an API in my page?
Only if you sanitise and escape. Treat every field as untrusted: strip tags and decode entities on the way in, validate dates and URLs strictly, and escape on output with esc_html, esc_attr and esc_url in PHP. In JavaScript, build elements and set textContent, and never assign API data to innerHTML. A source can be hacked or can change, so do not assume its content is clean.
Why does the list not show events beyond the first hundred?
The WordPress REST API returns at most one hundred items per page. The response headers report the total number of pages, so a larger source needs your code to request further pages, with a sensible upper limit on how many you will fetch, and to merge them before caching. Often a better answer is to ask the source for only upcoming items, or to request fewer fields, so one page is enough.
Can I add Query Filters or live search to an API loop?
No. The Bricks documentation states that API query loops do not support Query Filters or live search. If you need filtering, searching or sorting over external content, build it yourself with a server-side function and your own controls, use browser-side filtering on a small public list, or sync the external data into WordPress as posts or terms and use the normal filtered query loop.



