Delete Users from a WordPress Website once they Unsubscribed from a List

If you need a more deep synchronization between WordPress and MailChimp, take a look at my plugin.

Create a Webhook inside MailChimp

Actually there are two ways of creating MailChimp webhooks – via the dashboard and via the MailChimp API. In this tutorial we will talk about the first method, but if you need a way to create webhooks in code, check this tutorial.

To create a webhook, in your MailChimp dashboard go to Lists, select one and in a dropdown menu Settings select Webhooks.

Webhook settings page will look something like this:

Configure unsubscribe event for a MailChimp webhook

Delete a user once the webhook is fired

Once you created a webhook, let’s configure your WordPress website the proper way. Actually, you do not even have to have much coding knowledge, just insert the below code to your current theme functions.php (better a child theme or a custom plugin).


add_action( 'init', 'misha_user_delete_webhook');
 
function misha_user_delete_webhook(){

	// exit the function in case it is not our hook
	if( empty( $_GET['process-webhook'] ) || empty( $_POST['type'] ) || $_GET['process-webhook'] != 'delete' )
		return;

	if( $_POST['type'] === 'unsubscribe' ) {

		// we must get user ID somehow, let's to it with get_user_by()
		$user = get_user_by( 'email', $_POST['data']['email'] );

		// wp_delete_user() is an Admin function and it won't work without this line
		require_once(ABSPATH . 'wp-admin/includes/user.php' );
		
		wp_delete_user( $user->ID );
		
	}
	
}

If users have some articles on your website and you do not want to delete all the content, to a second parameter pass a user ID, you would like to reassign the content to, example: wp_delete_user( $user->ID, 1 ).

Misha Rudrastyh

Misha Rudrastyh

I develop websites since 2008, so it is total of 14 years of experience, oh my gosh. Most of all I love love love to create websites with WordPress and Gutenberg, some ideas and thoughts I share throughout my blog.

Need some developer help? Contact me

Follow me on Twitter