user roles – wp_update_user very slow

Question

I am changing a user role with a custom endpoint. If the ID is incorrect, it fails right away and I get my error message. If it is successful however, the role is updated in the backend right away but I don’t get the 200 response quickly. It just seems to hang forever and eventually I get the response.I tried the code without actually updating the user ie: leaving out the wp_update_user bit and it is way faster.

add_action( 'rest_api_init', function () {

      register_rest_route( 'userapi/v1', 'change-role', array(
        'methods' => 'POST',
        'callback' => 'change_user_role',
        'permission_callback' => '__return_true',
      ) );
    } );
    
    function change_user_role() {
       $userId = filter_var($_POST['userId'], FILTER_SANITIZE_NUMBER_INT);
       $new_role="vip";
       $result = wp_update_user(array('ID'=>$userId, 'role'=>$new_role));
        
        if ( is_wp_error( $result ) ) {
            return new WP_Error( 'usr_error', $result, array( 'status' => 500 ) );
        } else {
           return new WP_REST_Response( array( 'message' => 'Update successful' ), 200 );
        }
    }

0
Tom J Nowell 7 months 2021-05-21T05:41:13-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse