How to Create Advanced Meta Box Relationship Queries in Bricks Builder

Written by

Jannick Nijholt

Published on

21/12/2024

Last update

21/12/2024
BlogUncategorized

Working with Meta Box relationships in Bricks Builder can be tricky when you need more than a basic connection. While Bricks provides a built-in relationship selector for Meta Box Relationships, it lacks the advanced filtering and ordering options you might need for a more complex project.

Below, we’ll explore how you can create your own custom queries for MB Relationships in Bricks. I’ll use a real-world example from one of my projects so you can adapt these steps to fit your own site, whether you’re filtering by date or adding custom ordering. Once you see how powerful the Meta Box Relationships API is, you’ll never want to rely on the basic query options again!

Understanding the Challenge

The default Meta Box relationship selector in Bricks has some limitations:

  • No advanced filtering (e.g., based on a custom field’s value or the current date).
  • No custom ordering of the results.
  • No way to limit the number of returned posts using filters like date or any other criteria.
A screenshot of the Bricks Query Loop editor showing none of the Query Filter options that can be used for normal post types
Example of all filtering options missing when setting up a Query Loop with a MB Relationship

Basically, Bricks just returns all connected post IDs without any extra logic. If you want to, for example, get only the next upcoming date or filter out past events, you can’t do that with the built-in tools.

The Solution: Custom Query Configuration

We’ll solve this by writing a custom query in PHP. In the example below, I needed to show the next upcoming celebration date for a holiday, ignoring any dates that have already passed, then ordering them by date. This same approach can be modified for any type of filter or ordering you need.

Step 1: Fetch Related Posts

First, we use the MB_Relationships_API::get_connected function to retrieve the posts that are connected through our specific Meta Box relationship. Think of this as the crucial first step that gets the raw data we’ll filter and sort later.

$related = MB_Relationships_API::get_connected([
    'id' => 'holiday-celebration', // Relationship name
    'to' => get_the_ID(),          // Get connections to the current post
]);

Here’s what’s happening:

  • id: The relationship name (from Meta Box settings).
  • to: We’re requesting posts connected to the current post (i.e., get_the_ID()).

Step 2: Extract Post IDs

Next, we convert the fetched posts into a simple array of IDs using wp_list_pluck. This makes it easy to work with the WordPress query system, which often relies on arrays of post IDs.

$related_post_ids = wp_list_pluck($related, 'ID'); 

Step 3: Handle Empty Relationships

If there are no connected posts at all, we need a fallback. The example below forces the query to return no results by using post__in => [0]. It also keeps the same structure (like meta_query) so we don’t cause errors down the line.

if ( empty( $related_post_ids ) ) {
    return [
        'post_type'      => 'celebration',
        'posts_per_page' => 1,
        'post__in'       => [0], // Force no results
        'meta_query'     => [
            [
                'key'     => 'celebration_date',
                'value'   => date( 'Y-m-d' ), // Current date
                'compare' => '>=', // Future dates only
                'type'    => 'DATE'
            ]
        ],
        'meta_key'       => 'celebration_date',
        'orderby'        => 'meta_value',
        'order'          => 'ASC',
        'bricks_force_run' => true,
    ];
}

This returns no posts (due to [0]), but still runs a valid query. That way, Bricks doesn’t break when no relationships exist.

Step 4: The Main Query

If there are connected posts, here’s the final query that includes only those post IDs, filters out past dates, and orders the results by their “celebration_date” field.

return [
    'post_type'      => 'celebration',
    'posts_per_page' => 1,
    'post__in'       => $related_post_ids, // Include only related posts
    'meta_query'     => [
        [
            'key'     => 'celebration_date',
            'value'   => date( 'Y-m-d' ), // Current date
            'compare' => '>=', // Future dates only
            'type'    => 'DATE'
        ]
    ],
    'meta_key'       => 'celebration_date',
    'orderby'        => 'meta_value',
    'order'          => 'ASC',
    'bricks_force_run' => true, // Ensure Bricks processes this query
];

Key things to notice:

  • post_type and post__in work together to filter only the connected posts of the correct type.
  • meta_query uses a date comparison to show only future dates (or today onward).
  • meta_key, orderby, and order arrange them from earliest upcoming date to the latest.
  • bricks_force_run tells Bricks to run this query even though we already have a custom query in place.

Conclusion

This code might look like a lot at first, but once you see it in action, it’s straightforward to adjust for all kinds of filtering and sorting needs—far beyond what the default relationship selector allows. If you ever need to customize results based on Meta Box relationships, keep this snippet as a reference. It’s one of those techniques that can save you a ton of time (and frustration) when you’re working in Bricks!

The Full Code

In case you’re interested in the full code, as how it’s being used for my use case, this is it!

// Step 1: Fetch related posts using Meta Box Relationships API
$related = MB_Relationships_API::get_connected([
    'id' => 'holiday-celebration', // Relationship name defined in Meta Box
    'to' => get_the_ID(),          // Get connections to the current post
]);

// Step 2: Extract related post IDs
$related_post_ids = wp_list_pluck( $related, 'ID' );

// Step 3: Handle the case where no relationships exist
if ( empty( $related_post_ids ) ) {
    return [
        'post_type'      => 'celebration',
        'posts_per_page' => 1,
        'post__in'       => [0], // Force no results
        'meta_query'     => [
            [
                'key'     => 'celebration_date',
                'value'   => date( 'Y-m-d' ), // Current date
                'compare' => '>=',           // Future dates only
                'type'    => 'DATE'
            ]
        ],
        'meta_key'       => 'celebration_date',
        'orderby'        => 'meta_value',
        'order'          => 'ASC',
        'bricks_force_run' => true, // Ensure Bricks processes this query
    ];
}

// Step 4: Main query if relationships exist
return [
    'post_type'      => 'celebration',
    'posts_per_page' => 1,
    'post__in'       => $related_post_ids, // Include only related posts
    'meta_query'     => [
        [
            'key'     => 'celebration_date',
            'value'   => date( 'Y-m-d' ), // Current date
            'compare' => '>=',           // Future dates only
            'type'    => 'DATE'
        ]
    ],
    'meta_key'       => 'celebration_date',
    'orderby'        => 'meta_value',
    'order'          => 'ASC',
    'bricks_force_run' => true, // Ensure Bricks processes this query
];
Profile Picture of Jannick Nijholt

Question, comment or an idea?

Shoot me an email!
You can reach me on [email protected]