可能使用insert_user_meta (内部wp_insert_user()
, 也称为wp_update_user()
) 也可能是阻止注册额外代理的可行方法。set_user_role 可能还需要采取措施防止现有用户获得代理角色。
// Maybe prevent setting new users to agent role
function new_user_check_roles( $meta, $user, $update ) {
$max_agents = 30;
$agents = get_users( array( \'role\' => \'agent\' ) );
$agents = count( $agents );
if ( $max_agents != $agents ) {
return $meta;
}
if ( in_array( \'agent\', $user->roles ) ) {
$user->set_role( \'subscriber\' );
}
if ( isset( $meta[\'role\'] ) && \'agent\' == $meta[\'role\'] ) {
$meta[\'role\'] = \'subscriber\';
}
return $meta;
}
add_filter( \'insert_user_meta\', \'new_user_check_roles\', 10, 3 );
// Maybe prevent setting existing user to agent role
function set_roles_check_role( $user_id, $role, $old_roles ) {
$max_agents = 30;
$agents = get_users( array( \'role\' => \'agent\' ) );
$agents = count( $agents );
if ( $max_agents != $agents ) {
return;
}
if ( \'agent\' !== $role ) {
return;
}
$user = new WP_User( user_id );
$user->set_role( \'subscriber\' );
}
add_action( \'set_user_role\', \'set_roles_check_role\', 10, 3 );