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:
Create Books and Authors custom post type using ACF plugin and add few posts.
In ACF > Field Groups > Add New, let’s call it ‘Author Fields’. Here, create a new field type ‘Relationship’ and call it ‘List of Books’.
Under ‘Filter by Post Type’, select ‘Book’.
Under ‘Filters’, leave only ‘Search’ checked.
In Location Rules, set this to apply to Author post type
Save changes. Now you will be able to select books when creating authors.
In ACF > Field Groups > Add New, let’s call it ‘Book Fields’. Here, create a new field type ‘Relationship’ and call it ‘Authors of the Book’.
Under ‘Filter by Post Type’, select ‘Author’.
Under ‘Filters’, leave only ‘Search’ checked.
In Location Rules, set this to apply to Book post type
Save changes. Now you will be able to select authors when creating books.
Now, let’s synchronize these two custom fields so that when you create a book and select an author, you don’t need to go to the author page and select a book there too. Go to ACF > Author Fields > click on the field ‘List of Books’. In the header panel, click on ‘Advanced’, turn on ‘Bidirectional’, and below, select the Target Field ‘Authors of the Book’.
Do the same for Book fields > Authors of the book > Advanced > select List of books
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:
return ['post_type' => 'authors',
'posts_per_page' => -1,
'meta_query' => [
[
'key' => 'list_of_books',
'value' => '"'. get_the_ID() .'"',
'compare' => 'LIKE'
]
]
];
Make sure that the ‘post_type’ matches your actual custom post type and the key is the correct ACF field name applied to authors; in our case, it is ‘list_of_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.