Blog

Only allow certain domains to be registered on your WordPress or WooCommerce site.

March 2, 2018

If you want to limit domain registration on your website, that is possible.

For example, if you only want to allow people who have yahoo mail and gmail accounts to register on your site but not everyone else, here are the codes that you will need.

This is a little tricky though because the WordPress and WooCommerce functions that handle these registrations are different from each other. WordPress uses the register_post hook, while WooCommerce uses woocommerce_register_post hook. But your code runs similarly.

Here is the code if you want to limit domain registration on the WordPress registration (WP-Login) page:

function is_valid_email_domain($login, $email, $errors ){

	$valid_email_domains = array("gmail.com", "yahoo.com");// allowed domains
	$valid = false; // sets default validation to false
	
	foreach( $valid_email_domains as $d ){ //loop thru these domains
		$d_length = strlen( $d ); //Returns the length of the string.
		$current_email_domain = strtolower( substr( $email, -($d_length), $d_length)); //return a portion of the email
		if( $current_email_domain == strtolower($d) ){
			$valid = true; //set to true if the email is valid
		break;
	}
 }
 // Return error message for invalid domains
 if( $valid === false ){
	$errors->add('domain_whitelist_error',__( 'Registration is only allowed from selected approved domains. If you think you are seeing this in error, please contact the system administrator.' ));
	}
 }

add_action('register_post', 'is_valid_email_domain',10,3 ); //Hook this function to the WordPress hook function.

Note: You have to enable the Anyone Can Register option on your site settings to see if this works.

And here is the code if you want to hook it on the WooCommerce registration page:

function is_valid_registration_email_domain( $username, $email, $validation_errors ){
	$valid_email_domains = array( 'gmail.com', 'yahoo.com' ); // Allowed domains
	$valid = false; // sets default validation to false
	
	foreach( $valid_email_domains as $d ){
		$d_length = strlen( $d );
		$current_email_domain = strtolower( substr( $email, -($d_length), $d_length));
		
		if( $current_email_domain == strtolower($d) ){
			$valid = true;
			break;
		}
	}

	// Return error message for invalid domains
	if( ! $valid ){
		$error_text = __( "Registration is only allowed from selected approved domains. If you think you are seeing this in error, please contact the system administrator.", "woocommerce" );
		$validation_errors->add( 'domain_whitelist_error', $error_text );
	}
}
add_action('woocommerce_register_post','is_valid_registration_email_domain', 10, 3 ); //Hook this function to the WooCommerce hook function.
Share