Gravity forms posted a function that can assign extra role for a WordPress user upon Registration. Here is the function:
add_action( 'gform_user_registered', 'add_user_role', 10, 3 );
function add_user_role( $user_id, $feed, $entry ) {
// get role from field 5 of the entry.
$selected_role = rgar( $entry, '5' );
$user = new WP_User( $user_id );
$user->add_role( $selected_role );
}
It works well for assigining extra one role.
I am wondering how can I modify it to assign more many roles.
For example. There are 2 fields in the registration form: gender and country. I created roles with these 2 fields values.
So when a user register, he should be assigned to 2 roles or more according to the fields I will create. Male role, USA role,.. Etc.
I am doing all of this because I want to show the content on the website based on user role in the elementor conditional display.
I tried to duplicate the line:
$selected_role = rgar( $entry, '5' );
And modifying the field number, but it only assigns one of them.
One approach is to add the multiple roles to an array and loop through, adding each to the user:
add_action( 'gform_user_registered', 'add_user_role', 10, 3 );
function add_user_role( $user_id, $feed, $entry ) {
$selected_roles = array();
$selected_roles[] = rgar( $entry, '5' );
$selected_roles[] = rgar( $entry, '7' );
$user = new WP_User( $user_id );
foreach ( $selected_roles as $selected_role ) {
$user->add_role( $selected_role );
}
}