Search⌘ K
AI Features

Using Single REST API Endpoint for Multiple Post Types

Explore how to create a single WordPress REST API endpoint that fetches multiple post types. Learn to structure and customize search results with author info, thumbnails, excerpts, and custom fields to enhance your theme development skills.

In the last lesson, we created a custom query to fetch posts of teacher post type and returned them on the custom REST API endpoint. The school_search_results function is reproduced below:

<?php
function school_search_results(){
$args = array(
'post_type' => 'teacher'
);
$teacherPosts = new WP_Query($args);
$teacherResults = array();
while($teacherPosts->have_posts()){
$teacherPosts->the_post();
array_push($teacherResults, array(
'title' => get_the_title(),
'permalink' => get_the_permalink()
)); }
return $teacherResults;
}
school_search_results() function

To query for multiple post types, we can provide an array of all the post types we want our query to fetch. Also remember to set posts_per_page to -1 to view all the results otherwise only ten results will be displayed.

Since we are querying for multiple post types, we have changed the variables $teacherPosts to $allPosts and $teacherResults to $allResults.

<?php
function school_search_results(){
$args = array(
'post_type' => array('post', 'page', 'course', 'teacher', 'event'),
'posts_per_page' => -1
);
$allPosts = new WP_Query($args);
$allResults = array();
while($allPosts -> have_posts()){
$allPosts -> the_post();
array_push($allResults, array(
'title' => get_the_title(),
'permalink' => get_the_permalink()
));
}
return $allResults;
}
Querying for multiple post types

With the above array of arguments, the WP_Query will fetch results for all posts, pages, courses, teachers and events from the database. The results can be viewed at our search route /wp-json/excellence/v1/search.

Sorting results based on post type

The ...