Metabox Bidirectional relationships in Breakdance

Tony Nguyen
Tony Nguyen
April 14, 2024

Let’s say you have a custom post type ‘Books’, and now you want to create another custom post type ‘Authors’ and connect it with ‘Books’. This is the current state:

Before

and here is desired result with authors for each book in a loop:

After

Step 1

Make sure you have Metabox and Metabox AIO plugins installed. Create Books and Authors custom post type using Metabox plugin and add few posts.

Step1

Step 2

In Metabox > Relationships > New Relationship, let’s call it ‘Authors to Books’.

Under From select post type “Book”.

Under To select posty type “Author”

Publish this relationship. Make sure to remember relationship ID, we will need it later:

Step2

Step 3

Go to Author or Book posts and asign related posts:

Step3 1

Step 4

Now, let’s create Global Blocks for books and authors. We want to display a list of books, and inside each book’s card, we want to display its author(s).

First, let’s create a list of authors. Go to Breakdance > Global Blocks > and add a new Global Block called ‘Author List’. Then, open it with the Breakdance Builder. For its structure, add a Div. Inside the Div, add an image and text; for the image, fetch the featured image, and for the text, fetch the post title. Style them accordingly.

Step5

Go back to Global Blocks and create a new one called ‘Books Card’, then open it with the Breakdance Builder. Add an image, a heading, and a text paragraph. Fetch the featured image for the image, the post title for the heading, and the post excerpt for the text paragraph.

Now, add a Post Loop Builder inside this global block. Select the ‘Author List’ Global Block we created previously. For the query, select ‘Array’ and paste this code:

$author_ids = MB_Relationships_API::get_connected([
    'id'   => 'authors-to-books',  // Make sure this relationship ID is correct
    'from' => get_the_ID(),        
    'field' => 'from',
]);

if (!empty($author_ids)) {
    $author_ids = array_map(function($post) {
        return $post->ID;  // Extracting the ID from the WP_Post object.
    }, $author_ids);
}
return [
    'post_type' => 'authors',
    'posts_per_page' => -1,
    'post__in' => !empty($author_ids) ? $author_ids : array(0),
    'fields' => 'ids' // Remove this if you need full author objects.
];

Make sure that the ‘post_type’ matches your actual custom post type and the id is the correct Metabox relationship ID we created before, in our case it is ‘authors-to-books’.

Step 5

Create a new page. Add a Post Loop Builder, select the ‘Books Card’ Global Block, and for the post type, select ‘Books’. Style it as desired.

Find more about Headspin UI

Headspin Logo
1.3.0
Built with
Breakdance
and
Headspinui
@ 2024 HeadspinUI. All rights reserved.