我真的被这件事难住了。我已经知道如何允许从某些电子邮件域注册。但是,我只想限制一种用户类型。例如,“ROLE1”可以使用任何电子邮件地址注册,但“ROLE2”仅限于,比如gmail&;雅虎账户。
这就是我现在拥有的
<?php
/**
* Handles/processes registration forms data.
*/
add_action( \'user_register\', \'_hrb_user_register_role\' );
/**
* Assigns the selected role to the user being registered.
*/
function _hrb_user_register_role( $user_id ) {
if ( empty( $_POST[\'role\'] ) ) {
return;
}
$valid_roles = array_keys( hrb_roles() );
$role = $_POST[\'role\'];
// make sure we always get a valid role on registration
if ( empty( $role ) || ! in_array( $role, $valid_roles ) ) {
$role = HRB_ROLE_BOTH;
}
wp_update_user( array ( \'ID\' => $user_id, \'role\' => $role ) );
}
/**
* Filter email by role.
*/
if( $role = HRB_ROLE1 ) {
function is_valid_email_domain($login, $email, $errors ){
$valid_email_domains = array("gmail.com", "yahoo.com");// whitelist email domain lists
$valid = 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;
}
}
// if invalid, return error message
if( $valid === false ){
$errors->add(\'domain_whitelist_error\',__( \'<strong>ERROR</strong>: you can only register using gmail or yahoo email address!\' ));
}
}
add_action(\'register_post\', \'is_valid_email_domain\',10,3 );
}
SO网友:luke
您将要签出registration_errors 滤器确保角色已在特定注册表中发布。您必须在筛选器中检查角色和电子邮件是否有效,而不是有条件地添加您的操作。
add_action( \'registration_errors\', \'wpse_248123_registration_errors\' );
function wpse_248123_registration_errors( $sanitized_user_login, $user_email, $errors ) {
if ( empty( $_POST[\'role\'] ) ) {
$errors->add( \'empty_role\', __( \'<strong>ERROR</strong>: The role is invalid.\' ) )
}
if ( \'ROLE1\' === $_POST[\'role\'] && !wpse_248123_is_valid_email_domain( $user_email ) ) {
$errors->add( \'invalid_email_for_role\', __( \'<strong>ERROR</strong>: The email address isn’t allowed for this role.\' ) )
}
return $errors;
}
function wpse_248123_is_valid_email_domain( $email = \'\' ) {
$email = (string) $email;
$valid = false;
if ( empty( $email ) ) {
return $valid;
}
$valid_email_domains = array("gmail.com", "yahoo.com");// whitelist email domain lists
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 $valid;
}