Search code examples
wordpresswordpress-rest-api

WordPress REST API delete User


Is there a Possibility with WordPress REST API to allow a user to delete his own User-Account? I need this for GDPR compliance.

Thanks in advance


Solution

  • Expanding on the code that Felix provided in his answer I think this variant should improve the code under both usability and security. With the previous code you could delete any user given you knew the id (which I don't think it's generally publicly available but better safe than sorry) and the email. You also had to pass both of them using the query parameters.

    With this variant you don't need to pass anything as it's just gonna delete the account of the user that's calling the endpoint making it theoretically also more secure.

    Feel free to correct me, WP is not my main occupation.

    add_action('rest_api_init', 'wp_rest_user_delete_endpoint');
    /**
     * Register a new route
     **/
    function wp_rest_user_delete_endpoint($request) {
        /**
         * Handles the request.
         */
        register_rest_route('ddevs/v1', 'me', array(
            'methods' => 'DELETE',
            'callback' => 'wc_rest_user_endpoint_deleteuser',
        ));
    }
    
    /**
     * The actual user deletion
     */
    function wc_rest_user_endpoint_deleteuser($request = null) {
    
        $id = get_current_user_id();
    
        // If the id is 0 it means the user is not logged in.
        if ($id != 0) {
            require_once(ABSPATH . 'wp-admin/includes/user.php');
            wp_delete_user($id);
            return new WP_REST_Response([
                'message' => 'User deleted successfully',
            ], 200);
        } else {
            return new WP_REST_Response([
                'message' => "User not authenticated.",
            ], 400);
        }
    }