Home > Software engineering >  How can I change the default user role during registration in WooCommerce unless the account is crea
How can I change the default user role during registration in WooCommerce unless the account is crea

Time:04-08

I want to assign a custom user role to customers who register on my website, unless the registration is done via the WooCommerce checkout form.

I have tried several things but nothing targets only the registration form on the login page. I have set up already a custom user role, called "registered_user".


This code works but targets both the registration form on the login page and when a user registers through checkout.

add_filter( 'woocommerce_new_customer_data', 'assign_custom_role' );
function assign_custom_role( $args ) {
    $args['role'] = 'registered_user';
    return $args;
}

It also adds an additional role, so now users have both "customer" and "registered_user" roles.

I have also tried adding a hidden form field <input type="hidden" name="front_end_reg_form"> to the WooCommerce form_login.php attempting to target the form with:

function add_user_role_frontend_reg( $user_id ) {

    if($_POST['front_end_reg_form'] == 'front_end_reg_form')
    {
        $user = new WP_User( $user_id );

        $user->remove_role( 'customer' );
        $user->add_role( 'registered_user' );
    }
}

add_action('user_register', 'add_user_role_frontend_reg', 10, 1);

Which the above code doesn't do anything. If I change the hook to add_filter( 'woocommerce_new_customer_data', 'add_user_role_frontend_reg' ); I get the error: Cannot create a user with an empty login name.

So I'm stuck. What am I doing wrong and how can I correct it?

CodePudding user response:

This can actually be done very easily by using the is_checkout() conditional tag, and if not, adjust the user role

So you get:

function filter_woocommerce_new_customer_data( $args ) {
    // Returns true when viewing the checkout page.
    if ( ! is_checkout() ) {
        $args['role'] = 'registered_user';
    }

    return $args;
}
add_filter( 'woocommerce_new_customer_data', 'filter_woocommerce_new_customer_data', 10, 1 );
  • Related