Skip to content

Instantly share code, notes, and snippets.

Last active August 4, 2016 08:16
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
In order to search all post-types using the WP REST-API, which is not possible with the API, you can use this piece of code to search for all specified post-types. Replace all the 'POSTTYPE' parts with your CPT's slug, and it will be searchable in 1 query. You can also add additional CPT's. Using the ?embedded=true, you get all the embedded data!
add_action('rest_api_init', function () {
register_rest_route('mvaessen/v1', '/search', array(
'methods' => 'GET',
'callback' => 'search_all_endpoint',
function search_all_endpoint(WP_REST_Request $request)
//first get all posts through the normal WP_Query, to make this determine the order of display
$query = $request['query'];
$posts_per_page = -1;
$paged = 1;
if (isset($request['posts_per_page'])) {
$posts_per_page = $request['posts_per_page'];
if (isset($request['paged'])) {
$paged = $request['paged'];
$query_args = [
's' => $query,
'post_type' => 'any',
'suppress_filters' => true,
'posts_per_page' => $posts_per_page,
'paged' => $paged
$query = new WP_Query($query_args);
//prepare controllers for the required post-types
$postController = new WP_REST_Posts_Controller('post');
$pageController = new WP_REST_Posts_Controller('page');
//To add additional post-types
//$POSTTYPEController = new WP_REST_Posts_Controller('POSTTYPE');
$output = [];
//loop through the WP_Query results, and get the objects as proper WP REST-API objects
foreach ($query->posts as $item) {
$request = [
'id' => $item->ID
switch ($item->post_type) {
case 'post':
$output[] = $postController->prepare_response_for_collection(
case 'page':
$output[] = $pageController->prepare_response_for_collection(
//To add additional post-types
/*case 'POSTTYPE':
$output[] = $POSTTYPEController->get_items($request);
$response = rest_ensure_response( $output );
$response->header( 'X-WP-Total', (int) $query->found_posts );
$response->header( 'X-WP-TotalPages', (int) $query->max_num_pages );
return $response;
//how to use: /wp-json/mvaessen/v1/search?_embed=true&posts_per_page=2&paged=1&query=looking+for+this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment