Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mvaessen
Last active August 4, 2016 08:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvaessen/8525d0989994e2d5a3b997f4fb10b39c to your computer and use it in GitHub Desktop.
Save mvaessen/8525d0989994e2d5a3b997f4fb10b39c to your computer and use it in GitHub Desktop.
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!
<?php
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(
$postController->get_item($request)
);
break;
case 'page':
$output[] = $pageController->prepare_response_for_collection(
$pageController->get_item($request)
);
break;
//To add additional post-types
/*case 'POSTTYPE':
$output[] = $POSTTYPEController->get_items($request);
break;*/
}
}
$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