Delete User From Woocommerce My Account Page

Deleting user is not good idea and it can be dangerous since it may cause whole WordPress Installation to break down. Having said that sometime we need to implement this functionality. For this you can implement the code below on function.php of your theme.

// Delete Account Functionality added on the edit form of my-account page.
add_action( 'woocommerce_after_my_account', 'woo_delete_account_button' ); 
function woo_delete_account_button() { 
	$delete_url = add_query_arg( 'wc-api', 'wc-delete-account', home_url( '/' ) ); 
	$delete_url = wp_nonce_url( $delete_url, 'wc_delete_user' ); 

//https://dev.rigorousweb.com/demo/mlb/wp-admin/users.php?action=delete&user=16&_wpnonce=9035d1a60e
	if ( ! current_user_can( 'manage_options' ) ) {
?>
		<a href="<?php echo $delete_url; ?>" class="button">Delete Account</a> 
<?php 	}
}

add_action( 'woocommerce_api_' . strtolower( 'wc-delete-account' ), 'woo_handle_account_delete' ); 	
function woo_handle_account_delete() { 
	if ( ! current_user_can( 'manage_options' ) ) { 
		$security_check_result = check_admin_referer( 'wc_delete_user' ); 
		if ( $security_check_result ) { 
require('./wp-admin/includes/user.php');
			wp_delete_user( get_current_user_id() ); 
			wp_redirect( home_url() ); 
			die(); 
		} 
	} 
}

Implementing the code above can sometime cause 500 error. In that case you can delete this line

require('./wp-admin/includes/user.php');

We can also use the plugin for these functionality.

Delete Me

WP Delete User Accounts

Source : https://gist.github.com/kloon/4951687

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.