Building a custom REST API
Building a REST api via the ASP_Query class
The WordPress built in REST API supports extension via the register_rest_route function. We can use that to build a custom REST interface to access the search results.
In the following examples the ASP_Query class is used in the REST API handler functions.
Simple search example
In this example a simple search is executed by sending the "s" and "id" arguments to the
/wp-json/ajax-search-pro/v0/search endpoint via a POST request.
What is this, and where do I put this custom code?
/**
Sample payload query arguments:
array(
's' => 'test',
'id' => 1
)
*/
function asp_custom_rest_handler( $data ) {
$defaults = $args = array(
's' => '',
'id' => -1
);
foreach ( $defaults as $k => $v ) {
$param = $data->get_param($k);
if ( $param !== null ) {
$args[$k] = $param;
}
}
$asp_query = new ASP_Query($args, $args['id']);
return $asp_query->posts;
}
// POST to: http://example.com/wp-json/ajax-search-pro/v0/search
add_action( 'rest_api_init', function () {
register_rest_route('ajax-search-pro/v0', '/search', array(
'methods' => 'POST',
'callback' => 'asp_custom_rest_handler',
));
});Sample request
Search with post taxonomy filters
In this example a simple search is executed by sending the "s" and "id" as well as "post_tax_filter" arguments to the
/wp-json/ajax-search-pro/v0/search endpoint via a POST request.
What is this, and where do I put this custom code?
Sample request
Last updated