REST API: How can I restrict a custom post type to only be accessible by authenticated users?

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?

1 Answer
1

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.

Leave a Comment