Limit BuddyPress registration by domain

I am currently running a few WordPress installations with the great BuddyPress plugin. If you don’t know this plugin yet: you can create your own social network using this plugin. For example, it is possible to add groups, forums, membership, and even “@” commenting and discussions (like Twitter). Pretty nifty, really.

One thing that stumped me for a while was how to limit registrations to a particular domain. In my case, I wanted to limit registration to users with EDU email addresses (because the network is affiliated with our Five College System).

As it turns out, the code is not too involved. I just had to disassemble a discontinued plugin to find it. In any case… it works well and can even be expanded to use a blacklist/whitelist approach. Below is the code that you need to put into your functions.php file in your template.

I am using this on a single-site installation with the default BuddyPress template, and the code below only checks for EDU, so your mileage might vary. Adapt the code as you see fit.

// Limit signup to EDU emails - could also be used for banning domains

// Function that checks and returns error
function bp_as_restrict_signup_domains( $result ) {

	// Send error if this test fails
	if ( bp_as_check_email_domains( $result['user_email'] ) ) {
		$result['errors']->add('user_email', __('You must use an EDU email to sign up!', 'bp-restrict-email-domains' ) );
	};
	return $result;

};

add_filter( 'bp_core_validate_user_signup', 'bp_as_restrict_signup_domains' );

// Helper function for the actual test
function bp_as_check_email_domains( $user_email ) {

	$email_domain = strtolower( substr( $user_email, 1 + strpos( $user_email, '@' ) ) );

	// Could check against array here too
	$is_edu = strpos( $email_domain , "edu" );

	if ($is_edu === false) {
		// Error will be raised
		return true;
	}
	else {
		return false;
	};

};

I just implemented a banning routine that is actually a bit cleaner than the one above. Here’s the code:

// ====================================
// Limit signup by banning domains
function bp_as_restrict_signup_domains( $result ) {

 $banned = array(
 'spam1.com', 
 'spam2.com'
 );
 $error = 'Your email domain has been the source of spam. Please use another email address.';

 $email = $result['user_email']; 
 $domain = array_pop(explode('@', $email));
if ( in_array($domain, $banned))
 {
 $result['errors']->add('user_email', __($error, 'bp-restrict-email-domains' ) );
 };
 return $result;
}
add_filter( 'bp_core_validate_user_signup', 'bp_as_restrict_signup_domains' );

Source:

Comments and Reactions