REST API: How can I restrict a custom post type to only be accessible by authenticated users?
-
14-12-2020 - |
Question
I have a custom post type
configured to be accessible via the WP Rest API v2.
How do I lock the access to this custom post type
so that only the authenticated users can perform GET
requests?
Solution
Looks like I found a snippet that do exactly that. It's from Daniel Bachhuber, the API developer.
add_filter( 'rest_authentication_errors', function( $result ) {
if ( ! empty( $result ) ) {
return $result;
}
if ( ! is_user_logged_in() ) {
return new WP_Error( 'restx_logged_out', 'Sorry, you must be logged in to make a request.', array( 'status' => 401 ) );
}
return $result;
});
This is posted in his gist on GitHub.
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange