Wordpress - WP REST API -- How to change HTTP Response status code?
You can return a WP_Error
object in which you define the status code. Here's a snippet from the REST API documentation:
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return new WP_Error( 'awesome_no_author', 'Invalid author', array( 'status' => 404 ) );
}
return $posts[0]->post_title;
}
In your case you could do something like:
return new WP_Error( 'page_does_not_exist', __('The page you are looking for does not exist'), array( 'status' => 404 ) );
The simplest way is to do this:
return new WP_REST_Response(null, 404);
Note: this is still a JSON response containing null
as the body. You'd have to hook into the rest output filters, and change it to text/plain
or something to output nothing.