Relationship fields that can be used in the supported custom field solutions, introduce many new possibilities for your WordPress projects.
Being able to display all related posts from another CPT on the current post is somewhat different than displaying a textfield on the current one.
Books and Writers
Let's consider the following example:
We have two Custom Post Types (CPT's), one called Writers and one called Books. Each writer can have multiple books. This is called a "one to many" relationship. Of course multiple writers can contribute to a single book, which can also makes it a "many to many" relationship, but for this example let's keep it at 1:n.
Advanced Custom Fields
If you are using Advanced Custom Fields to register your custom fields, you might want to consider adding an extra plugin called ACF Post-2-Post that can be found in the WP repository. This plugin will make sure that any relationship set to the writer (1 or more books) will also be set on the selected books itself. The books themselves also have a relationship, but to a writer. Without the Post-2-Post plugin, WP will have no way of knowing that.
Make sure to give both the Writer and Book CPT a relationship field that have the exact SAME name. The labels can be different, but the fieldnames need to match.
You can copy the text below and save it as a file on your computer. Make sure to name it with a .json extension. You can use it to import it into ACF Pro as two seperate fieldgroups, one for the CPT called "writer" and the other for the CPT called "book".
If done correctly, each time you save the edited Writer post and have selected one or more books as a relationship, each book will also be updated with the writer as the returned relationship. You will not have to go into each Book post to set the writer accordingly.
The relationship field itself returns an array of selected post ID's. If no relationships have been set, it will return either null (no value) or an empty array.
With Toolbox, you can use these post ID's to get either it's custom field data or get the post itself.
For this you will first need to add something that is described more in depth in the next section. It is called Timber Library, a plugin available in the WP repository. It uses the Twig templating engine, which allows you to mix php and html in a readable format.
If you examine the template in the image you can see it:
- Checks to see if there are at least 1 books related to the artist;
- Loops over the ID's in the __field__ array, each time assigning to the variable 'item';
- Creates or resets the variable 'book' and fetches it as a Post Object, so we can use Timber to output it's information easily;
- Display each book title in the relationship as a link;
Most of this template can be reused on the Book Single Post (or Themer Layout). You only need to change the text inside the <h2> tags!