Delete WordPress Users Once They Unsubscribe in Mailchimp

I already have a tutorial on how to subscribe a user to an audience after registration on WordPress website. It is know to find out how to do the opposite (from Mailchimp to WordPress).

I can also suggest your Simple Mailchimp Sync plugin that allows to do all that.

Create a Webhook in Mailchimp

There is also a separate complete tutorial about Mailchimp webhooks on my site if case you would like to learn more about them.

In order to create a webhook please go to a specific audience you’re creating a webhook for, then click Settings > Webhooks.

create a webhook in Mailchimp

Here we need to configure two things:

  1. URL on your website which is going to process the webhook. In case we are working with WordPress themes, we can use functions.php file, then the webhook can be any existing website page with a query parameter like ?delete-users=yes.
  2. Check “Unsubscribes” checkbox.

That’s all, let’s save the webhook and continue to the second step.

Delete a WordPress User Once the Webhook is Fired

Do not know where to insert the code?

add_action( 'template_redirect', 'misha_user_delete_webhook');

function misha_user_delete_webhook(){

	// exit the function in case it is not our hook
	if( empty( $_GET[ 'delete-users' ] ) || 'yes' !== $_GET[ 'delete-users' ] ) {
		return;
	}

	// check the action
	if( empty( $_POST[ 'type' ] ) || 'unsubscribe' !== $_POST[ 'type' ] ) {
		return;
	}

	// we can check the list ID to improve the security of a webhook
	// if( empty( $_POST[ 'data' ][ 'list_id' ] ) || 'abcdef12345' !== $_POST[ 'data' ][ 'list_id' ] ) {
	// 	return;
	// }

	// do the thing
	$user = get_user_by( 'email', $_POST[ 'data' ][ 'email' ] );
	if( $user ) {
		// we need it in order to make wp_delete_user() work
		require_once( ABSPATH . 'wp-admin/includes/user.php' );
		wp_delete_user( $user->ID );
	}
	exit;

}

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

Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X