Privacy PHP Intermediate

Anonymise Comments When a User Is Deleted

When you delete a user, keep their comments for the conversation but remove their name, email, website and IP address.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 21 lines
add_action( 'delete_user', function ( int $user_id ): void {
	$comments = get_comments( [
		'user_id' => $user_id,
		'status'  => 'all',
		'fields'  => 'ids',
		'number'  => 0,
	] );

	foreach ( $comments as $comment_id ) {
		$comment = get_comment( $comment_id );
		wp_update_comment( [
			'comment_ID'           => $comment_id,
			'comment_author'       => 'Former member',
			'comment_author_email' => '',
			'comment_author_url'   => '',
			'comment_author_IP'    => wp_privacy_anonymize_ip( (string) $comment->comment_author_IP ),
			'comment_agent'        => '',
			'user_id'              => 0,
		] );
	}
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

When a user account is deleted, WordPress keeps their comments, still showing their name, email and IP address. If someone asks you to delete their account, they likely expect that information to go too. This snippet anonymises their comments while keeping the discussion readable.

How it works

The delete_user action runs just before a user is deleted. The snippet finds all their comments, in any status, and updates each one with wp_update_comment(): the name becomes “Former member”, email, website and user agent are cleared, the IP address is shortened and the link to the user account is removed.

The comment text stays. If the comment itself contains personal details, edit or delete it separately.

Things to watch

  • This runs for every user deletion, including spam accounts.
  • Comments posted while logged out with the same email address aren’t linked to the account and aren’t changed. Use Tools → Erase Personal Data for those.

How to test it

Create a test user, post a comment as them, then delete the user. The comment should show “Former member” with no email.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only