I've made a custom endpoint for my REST API:
add_action( 'rest_api_init', function () {
register_rest_route( 'foo/v1', '/bar/', array(
'methods' => 'GET',
'callback' => 'foo_callback',
) );
} );
I normally have a WP query as my callback, but to simplify things let's pretend I'm just asking for certain parameters to be returned to me:
function foo_callback(){
$string = "";
if($_REQUEST['paged']){
$string .= $_REQUEST['paged'];
}
if($_REQUEST['posts_per_page']){
$string .= $_REQUEST['posts_per_page'];
}
return $string;
}
I'm also locking down my API so only logged-in users can access it, requiring an Application Password.
add_filter( 'rest_authentication_errors', function( $result ) {
if ( ! empty( $result ) ) {
return $result;
}
if ( ! is_user_logged_in() ) {
return new WP_Error( 'rest_not_logged_in', 'You're not logged in bozo.', array( 'status' => 401 ) );
}
return $result;
});
This API request with a single parameter works:
curl -X GET https://example.com/wp-json/foo/v1/bar?posts_per_page=1 -H "Authorization: Basic xxxxx"
This API request with a different parameter works:
curl -X GET https://example.com/wp-json/foo/v1/bar?paged=2 -H "Authorization: Basic xxxxx"
But this API request combining both parameters does not work:
curl -X GET https://example.com/wp-json/foo/v1/bar?posts_per_page=1&paged=2 -H "Authorization: Basic xxxxx"
In fact, it tells me "You're not logged in, bozo". Multiple parameters are somehow triggering my !is_user_logged_in() rule (although it throws up a generic error even if I remove that clause).
What am I doing wrong, and what's the correct way to allow multiple parameters in my endpoint?