Assign user roles based on BuddyPress profile field data on user registration
Are you looking for how to assign role to user based on profile field data for BuddyPress registration? It's simple.
We can use the "bp_core_activated_user" action which is called when user account gets activated. Since we plan to assign role based on profile field data, we will need to find the data.
To fetch BuddyPress profile field data, we will use xprofile_get_field_data() function.
Now, let us see an example of assigning role based on BuddyPress profile field data. For this example, I am creating a field named "Membership Type" as shown below
You can use any single valued field(Radio, select, text etc.).
Once I created it, the field became available on my registration page as shown below
Based on the above setup, here are the assumptions I am using to write the code
- We have a profile field with certain values
- We know what role we want to assign for these values
In my case, I wanted to assign "Contributor" for the Student and "Autohor" for Teacher.
Here is the actual code. Please put it in your bp-custom.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | /** * Assign role to user on BuddyPress registration, based on profile field data. * * @param int $user_id user id. */ function buddydev_assign_profile_field_based_role_on_registration( $user_id ) { $user = get_user_by( 'id', $user_id ); if ( ! $user ) { return; } //if we are here, we have the user object // to set role, we need to decide on a role and use $user->set_role('rolename')); $role = ''; // Profile field ID or Name that we will use to decide role. $field_name = 'Membership Type';// Change this with actual field id or Name. // let us fetch our profile field data $selected = xprofile_get_field_data( $field_name, $user_id, 'comma' ); //assuming single valued field. // let us find out which role should we assign if ( 'Student' === $selected ) { $role = 'contributor';// assigning 'Contributor' role. Change it s per your need. } elseif ( 'Teacher' === $selected ) { $role = 'author';// Change it to your preferred role. } // feel free to add other conditions. // if we found a role that we can assign, let us do it. if ( $role ) { $user->set_role( $role ); } } add_action( 'bp_core_activated_user', 'buddydev_assign_profile_field_based_role_on_registration' ); |
I have commented the code and explained as much as I can there. You will need to change the Filed Name, roles and the values in condition based on your use case.
Please feel free to use it, extend it as you please. If you need further help with the code, Please do post in our support forums.
Also, if you are looking for more control, You may try our BuddyPress Member Types Pro which allows you to assign member type, role, groups etc on BuddyPress user registration.
thank you ..you are a genuis