If you feel comfortable with php, here’s a gist from @imath to autojoin users to groups.
Modify it to add the member_type
A little different, BuddyPress Registration Groups
The first argument is an integer, not a string.
groups_join_group( $group_id, $user_id = 0 )
Since you are only handling 2 specific groups, you could hardcode the $group_id
.
groups_join_group( 3, $user_id );
Or you could get the id like this:
$group_id = groups_get_id( 'Teachers' );
This is super quick support.
Thank you guys
I have tested the groups_join_group function and it works now. Thanks @shanebp
However, the IF loop does not.
function set_default_group( $user_id ) {
$accounttype = get_user_meta( $user_id, 'I am a', true );
if ($accounttype == 'Student'){
groups_join_group( 1, $user_id );
}
elseif ($accounttype == 'Teacher'){
groups_join_group( 2, $user_id );
}
}
add_action( 'user_register', 'set_default_group', 10, 1 );
I have also tried @imath’s gist… It works well as-is for all new registered members to auto join selected groups.
But I need new members to join only specific groups based on the ‘I am a’ field (Student/Teacher).
So unfortunately the gist doesn’t help if I can’t even get my IF loop to work 🙁
It seems to be an issue with get_user_meta.
I have tried $accounttype = xprofile_get_field_data( 'I am a', $user_id );
instead of $accounttype = get_user_meta( $user_id, 'I am a', true );
but none of them work.
My field ‘I am a’ is part of the Primary Field Group (also shown on the registration form) and has only ‘Student’ and ‘Teacher’ as options.
Any idea what goes wrong?
If $accounttype
is a required field in your Base group, it will not be in usermeta.
Untested, but try:
function set_default_group( $user_id ) {
if ( empty( $user_id ) )
return;
$accounttype = xprofile_get_field_data( 'I am a', $user_id );
if ($accounttype == 'Student')
groups_join_group( 1, $user_id );
else
groups_join_group( 2, $user_id );
}
add_action( 'bp_core_activated_user', 'set_default_group', 11, 1 );
Thanks @shanebp.
bp_core_activated_user does a better job than user_register
It works with some additional {} as follows:
function set_default_group( $user_id ) {
if ( empty( $user_id ) ) {
return;
}
$accounttype = xprofile_get_field_data( 'I am a', $user_id );
if ($accounttype == 'Student') {
groups_join_group( 1, $user_id );
}
elseif ($accounttype == 'Teacher') {
groups_join_group( 2, $user_id );
}
}
add_action( 'bp_core_activated_user', 'set_default_group', 11, 1 );
May I ask what’s the purpose of
if ( empty( $user_id ) ) {
return;
}
?
It avoids failure and error or warning messages if $user_id
is missing.