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

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