0
votes

My wordpress site has two types of user. When they sign up, they nominate their user type, and I want to assign one of two roles, depending on which user type they are.

My user registration page has a radio button, where the new user chooses whether they between the two types of registration. Lets call the registration types 'Cat' and 'Dog' for the purpose of this discussion.

I have added a Cat/Dog radio button to the gravity form, where the user can select 'Dog' - the radio button defaults to 'Cat'. This field is 'RegisterAs'.

Gravity Form User Registration allows me to set a role on the new user. I choose 'Dog' for all new registrations

The gravity form used to gather the new user data has a confirmation to redirect them to a cat-or-dog page: Confirmation

The cat-or-dog page has a template assigned to it - let's call is 'cat-or-dog.php'. This contains this code:

<?php
/* Template Name: Cat or Dog */
if (isset($_GET['RegAs'])) {
if ($_GET['RegAs']=='Dog') {
global $current_user;
var_dump($current_user->roles);
$current_user->add_role('Dog');
echo "After:";
var_dump($current_user->roles);
die();

I would expect the output to show the roles changing from dog to cat. Instead, the output from this is the following:

array(1) { [0]=> string(6) "cat" } After:array(1) { [0]=> string(6) "cat" }

So it appears that the add_role does nothing!

Can anyone correct my code? Or perhaps there is another way to assign a role conditional on a radio button during user registration.

I want to use Gravity Forms with the User Registration plug in, as this is used throughout the site and I am not a collector of plugins.

Note that I have not removed the 'Cat' role yet - I am first wanting to overcome this add_role problem. Then I will work on removing the role.

1

1 Answers

0
votes

The gform_user_registered hook is provided by the Gravity Forms code to implement this.

https://www.gravityhelp.com/documentation/article/gform_user_registered/

At the very top of my theme functions.php file, I included this code:

function change_cat_dog_role( $user_id, $user_config, $entry, $user_pass ) {
    $question1 = rgar( $entry, '8' ); //field id 8


    if ( $question1 == 'Dog' ) {
        //update role
        $user_obj = new WP_User( $user_id );
        $user_obj->add_role( 'dog' );
    }
}

add_action( 'gform_user_registered', 'change_cat_dog_role', 11, 4 );

Note that the add role 'dog' is lower case, even though the role is actually proper case 'Dog'.