Wordpress 在Woocommerce中注册时根据电子邮件域自动设置自定义角色
我已经寻找了一个答案,但似乎没有工作,我希望有一个更好的看那里也如果问题是n00b 我正在尝试根据用户的电子邮件域(即custom domain.com)在注册时自动设置自定义角色(已定义) 到目前为止我已经试过了Wordpress 在Woocommerce中注册时根据电子邮件域自动设置自定义角色,wordpress,woocommerce,Wordpress,Woocommerce,我已经寻找了一个答案,但似乎没有工作,我希望有一个更好的看那里也如果问题是n00b 我正在尝试根据用户的电子邮件域(即custom domain.com)在注册时自动设置自定义角色(已定义) 到目前为止我已经试过了 add_action( 'user_register', 'wp234_set_role_by_email' ); function wp234_set_role_by_email( $user_id ){ $user = get_user_by( 'id', $user_i
add_action( 'user_register', 'wp234_set_role_by_email' );
function wp234_set_role_by_email( $user_id ){
$user = get_user_by( 'id', $user_id );
$domain = substr(
strrchr(
$user->data->user_email,
"@"
), 1
); //Get Domain
$contributor_domains = array( 'custom-domain.com' );
if( in_array( $domain, $contributor_domains ) ){
foreach( $user->roles as $role )
$user->remove_role( $role ); //Remove existing Roles
$user->add_role( 'author' ); //Add role.
}
}
我也尝试过答案代码,但运气不佳。您可以使用PHP函数检查客户的电子邮件地址是否包含特定字符串(域)
如果user\u register
钩子不起作用,并且您正在使用WooCommerce,您可以将其替换为在创建新客户时激活的钩子
如果多次使用同一个钩子请设置优先级,以确保函数在所有其他钩子之后运行(根据需要)
该代码已经过测试,可以正常工作。将其添加到活动主题的functions.php中
// set custom user role based on email
add_action( 'woocommerce_created_customer', 'wp234_set_role_by_email' );
function wp234_set_role_by_email( $user_id ) {
// initializes the control variable
$found = false;
// get user's email based on user id
$user_email = get_user_by( 'id', $user_id )->user_email;
// defines the domains to compare with
$contributor_domains = array( 'custom-domain.com' );
// for each domain
foreach ( $contributor_domains as $domain ) {
// if the email address contains one of the domains
if ( strpos( $user_email, $domain ) ) {
$found = true;
break;
}
}
// if it is found
if ( $found ) {
// gets the user's object
$user = new WP_User( $user_id );
// set the custom user role
$user->set_role( 'author' );
}
}