Delete user from frontend

Hi I am working on a frontend admin where a user must be able to delete his account. current_user() is a custom made function of me that retrieves the user meta data.

Does anyone know how I can make this work?

echo '<a class="remove" href="' . get_permalink() . '?remove_account">' . __( 'Click here to remove your account' ) . '</a>';

// Remove account
function terminate_account() {
    require_once( ABSPATH . 'wp-admin/includes/user.php' );
    wp_delete_user( current_user( 'ID' ) );
}

if( isset( $_GET['remove_account'] ) ) {
    add_action( 'init', 'terminate_account' );
}

Related posts

1 comment

  1. Taken directly form the wp_delete_user documentation:

    if(is_user_logged_in() && !empty($_GET['DeleteMyAccount'])) {
        add_action('init', 'remove_logged_in_user');
    }
    
    function remove_logged_in_user() {
        require_once(ABSPATH.'wp-admin/includes/user.php' );
        $current_user = wp_get_current_user();
        wp_delete_user( $current_user->ID );
    }
    

    Things to note:

    • Your code didn’t check if the user was logged in or not
    • by the time you’re printing the remove user link, the init action has already happened and finished, so your delete user wouldn’t work. That part of the code needs to be ran earlier, say in functions.php or a plugin

    edit:

    If you can place this in your themes function file:

    add_action('init', 'remove_logged_in_user');
    
    function remove_logged_in_user() {
        require_once(ABSPATH.'wp-admin/includes/user.php' );
        $current_user = wp_get_current_user();
        $success = wp_delete_user( $current_user->ID );
        wp_die('wp delete gave: <pre>"'.print_r($success).'"</pre>');
    }
    

Comments are closed.