Hello Friends, Few days ago I was developing a WordPress project in which I was required to add role chooser option on WooCommerce registration page, so Now I am sharing this code so that if anyone required this feature on their WordPress based ecommerce website so they can use this code.
To add on this feature just simply copy the code and paste it to theme’s functions.php file.
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 |
/* Add Role Choose Option on Registration */ //adding role select option on registration form function wooc_extra_register_fields() { global $wp_roles; ?> <p class="form-row form-row-wide"> <label for="reg_billing_phone">Select Role</label> <select name="role" class="input"> <?php foreach ( $wp_roles->roles as $key=>$value ) { // Exclude default roles such as administrator etc. Add your own if ( ! in_array( $value['name'], [ 'Administrator', 'Author', 'Editor', 'Shop Manager' ] ) ){ echo '<option value="'.$key.'">'.$value['name'].'</option>'; } } ?> </select> </p> <?php } add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' ); //saving role add_action( 'woocommerce_created_customer', 'update_user_role' ); function update_user_role( $user_id ) { $user_id = wp_update_user( array( 'ID' => $user_id, 'role' => $_POST['role'] ) ); } |
Comments