add_filter( 'rest_authentication_errors', function ( $access ) {
$error = new \WP_Error( 'rest_cannot_access', __( 'Only authenticated users can access the REST API.', 'disable-json-api' ), array( 'status' => rest_authorization_required_code() ) );
// $endpoints = availables free access endpoints
if ( isset( $_SERVER['REQUEST_URI'] ) && count( $endpoints = apply_filters( 'available_rest_api_endpoints', array() ) ) ) {
preg_match_all( '/^.+\/(.+)\?.*$/', $_SERVER['REQUEST_URI'], $matches );
if ( isset( $matches[1] ) ) {
$endpoint = array_pop($matches[1]);
if ( in_array( $endpoint, $endpoints ) ) {
return $access;
}
}
}
if ( ! is_user_logged_in() ) {
return $error;
} else {
$user = wp_get_current_user();
$role = $user->roles[0];
// currently only admin has a free access
if ( ! in_array( $role, apply_filters( 'rest_enabled_roles', array( 'administrator' ) ) ) ) {
return $error;
}
}
return $access;
} );
available_rest_api_endpoints: default = array(), output must be an array
rest_enabled_roles: default = just admin, output must be an array of valid roles
rest_enabled_roles: default = just admin, output must be an array of valid roles
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.