fbpx
Home » Blog » How to Find Duplicate Email Addresses in WordPress

How to Find Duplicate Email Addresses in WordPress

Quickly find duplicate email addresses in the WordPress users table in the database so you can maintain a unique email address per user.

I have used this code snippet in countless projects over the years.

Membership sites do a good job of enforcing unique email addresses per WordPress user but sometimes duplicate email addresses can slip through the cracks.

This may be due to user migrations, data imports or custom registration forms.

If your site uses functions that assume each WordPress user has a unique email address, admins need to know what they are so they can be fixed.

I run the following code in a weekly cron job on my membership sites.

	/**
	 * Weekly job to check for duplicate email addresses in users table
	 * Send an email to site admins if duplicate email addresses are found
     *
     * $results will return an empty array if no duplicates found
     * $results will return an array of objects with the properties:
     *      user_email      The email address
     *      NumOccurrences  The number of duplicates
	 */
	public function zpd_weekly_duplicate_email_check(){
		global $wpdb;

		// Search for duplicate email addresses
		$results  = $wpdb->get_results(
			"SELECT user_email, COUNT(user_email) 
			AS NumOccurrences
			FROM $wpdb->users
			GROUP BY user_email
			HAVING (COUNT(user_email) > 1)"
		);

		// Check the results
		if( !empty( $results ) ){
		    // Duplicate emails found - loop through them all
			$email_msg = sprintf( 'The following duplicate emails were found in the users table on the %s site: ', get_bloginfo( 'name' ) );
			$email_str = '';
			foreach( $results as $email_address ){
				$email_str .= "\n" . $email_address->user_email . ' ' . sprintf("(occurances x%s) ", $email_address->NumOccurrences );
			}

			// Send email to admins
			wp_mail( get_bloginfo( 'admin_email' ), get_bloginfo( 'name' ) . ': Duplicate Emails Found', $email_msg . $email_str );
		} else {
		    // No duplicate emails found - do something or nothing...
		}
	}

Modify the code for your own needs and let me know in the comments below if it was useful.

Keep In Touch

Wil

Wil is a dad, consultant, developer, conference organiser, speaker and business mentor. He co-organizes the WordPress Sydney meetup group and has been on the orgnising committee for WordCamp Sydney since 2014. He speaks at many technical events and contributes to the WordPress open source project. His likes are chillies, craft beer and electrogravitics.
If You Enjoyed This Post
Join Our Newsletter
Give it a try, you can unsubscribe anytime.
Close