Post Type Relationships in Search Logic
Learn about making the search logic aware of post type relationships.
We'll cover the following...
We have linked teachers and events to a course in the Creating Post Relationships lesson. This relationship should be reflected in the search results too. If a user searches for Artificial Intelligence, not only do we want the results to contain the course itself, but also the teachers and events related to the Artificial Intelligence course. As of now, when the custom REST API responds, the courses
array contains a result while the teachers
and events
arrays are empty.
The search logic implemented in the school_search_results
function in the search-route.php
file (inside the inc folder) uses a custom query to pull in data based on the search term. To add relationships, we can write another custom query (based on the search term) that fetches all the related data.
Custom query for related teachers and events
Open the search-route.php
file from the inc folder and navigate to the school_search_results
function. We have a WP_Query
object called $allPosts
. This object is used in a while
loop where we populate the $allResults
array.
To write a second query, it is important to call the wp_reset_query()
...