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:
and here is desired result with authors for each book in a loop:
Make sure you have Metabox and Metabox AIO plugins installed. Create Books and Authors custom post type using Metabox plugin and add few posts.
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:
Go to Author or Book posts and asign related posts:
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.
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’.
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.