Displaying Reverse Relationship
Learn to display the reverse relationship by displaying the related events in the course post.
The related_courses
custom field displayed on the event and teacher posts links the course post type with the event and teacher post types. When creating an event or teacher post, we can choose the related courses. In the previous lesson, we saw how to display the relationship on the event and teacher posts.
In this lesson, we will focus on displaying the reverse relationship, i.e., displaying the events and teachers on a course post. This is not as straightforward as displaying the simple forward facing relationship.
The custom field which links the course and event post types is associated with the event post type. So how do we get the information of that custom field in the course post type? The answer lies in custom queries.
Custom query to get related teachers
The related_courses
custom field can be accessed on a teacher post using the get_field()
function to displays the courses taught by a teacher. On a course page, we can use a custom query to fetch all teachers teaching that course by looking at the related_courses array.
Open the single-course.php
file. Locate where the post content is being displayed in the while
loop. We will display the teachers right below the content. To set up the custom query, we will create an array of arguments.
The query will look for posts of teacher post type (
'post_type' => 'teacher'
).It will display all the related teachers (
'posts_per_page' => -1
).The teachers will be alphabetically ordered (
'orderby' => 'title'
).The default sort order is descending, but we will change it to ascending (
'order' => 'ASC'
).The meta query will check for the desired condition: the
related_courses
custom field has the post ID of the current course.The
related_courses
custom field is thekey
.The comparison operator is
LIKE
.The
value
to compare is the ID of the current course. To get the ID, we have used theget_the_ID()
function which is wrapped in quotation marks to get an exact match (as the IDs are stored after serialization)
The array of arguments is shown below:
Get hands-on with 1400+ tech skills courses.