Skip to content

Instantly share code, notes, and snippets.

@milindmore22
Last active January 27, 2018 11:42
Show Gist options
  • Save milindmore22/44f208d5773bf059f0e6491e942979fe to your computer and use it in GitHub Desktop.
Save milindmore22/44f208d5773bf059f0e6491e942979fe to your computer and use it in GitHub Desktop.
cached_get_item_permissions_check
<?php
function cached_get_item_permissions_check( $request ) {
$error = new WP_Error( 'rest_user_invalid_id', __( 'Invalid user ID.' ), array( 'status' => 404 ) );
if ( (int) $request['id'] <= 0 ) {
return $error;
}
$user = get_userdata( (int) $request['id'] );
if ( empty( $user ) || ! $user->exists() ) {
return $error;
}
if ( is_multisite() && ! is_user_member_of_blog( $user->ID ) ) {
return $error;
}
if ( is_wp_error( $user ) ) {
return $user;
}
$types = get_post_types( array( 'show_in_rest' => true ), 'names' );
if ( get_current_user_id() === $user->ID ) {
return true;
}
if ( 'edit' === $request['context'] && ! current_user_can( 'list_users' ) ) {
return new WP_Error( 'rest_user_cannot_view', __( 'Sorry, you are not allowed to list users.' ), array( 'status' => rest_authorization_required_code() ) );
} elseif ( ! cached_count_user_posts( $user->ID, $types ) && ! current_user_can( 'edit_user', $user->ID ) && ! current_user_can( 'list_users' ) ) {
return new WP_Error( 'rest_user_cannot_view', __( 'Sorry, you are not allowed to list users.' ), array( 'status' => rest_authorization_required_code() ) );
}
return true;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment