I have a custom endpoint where I want to change HTTP response status to 404 in certain scenarios (e.g post does not exist). How can I do that? Here is an example of custom endpoint:
function af_news_single( \WP_REST_Request $data ) {
global $wpdb;
$year = (int) $data['year'];
$month = (int) $data['month'];
$day = (int) $data['day'];
$slug = $data['slug'];
$date = "{$year}-{$month}-{$day}";
$news = $wpdb->get_row(
$wpdb->prepare(
"SELECT
DATE_FORMAT(post_date, %s) as `post_date`,
`post_title`,
`post_name`,
`post_content`
FROM {$wpdb->posts}
WHERE
`post_status` = 'publish' AND
`post_type` = 'post' AND
`post_name` = %s AND
`post_date` BETWEEN %s AND %s + INTERVAL 1 DAY
LIMIT 1
", '%Y-%m-%dT%TZ', $slug, $date, $date
)
);
if ( $news ) {
$news->post_title = qtranxf_translate( $news->post_title );
$news->post_content = wpautop( qtranxf_translate( $news->post_content ) );
} else { /* How to change response code? */ }
return [ 'data' => $news ];
}
How can I change response code in this function?
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 ) );