Change user role if checkout custom checkbox is checked in WooCommerce



PHP Snippet 1:

add_action( 'woocommerce_after_order_notes', 'custom_checkout_field_with_wholesale_option' );
function custom_checkout_field_with_wholesale_option( $checkout ) {

    if( current_user_can( 'wholesale_customer' ) ) return; // exit if it is "wholesale customer"

    echo '<div id="wholesale_checkbox_wrap">';
    woocommerce_form_field('wholesale_checkbox', array(
        'type' => 'checkbox',
        'class' => array('input-checkbox'),
        'label' => __('Would you like to apply for a wholesale account?'),
        'placeholder' => __('wholesale'),
        'required' => false,
        'value'  => true
    ), '');
    echo '</div>';

}

// Conditionally change customer user role
add_action( 'woocommerce_checkout_update_order_meta', 'wholesale_option_update_user_meta' );
function wholesale_option_update_user_meta( $order_id ) {
    if ( isset($_POST['wholesale_checkbox']) ) {
        $user_id = get_post_meta( $order_id, '_customer_user', true ); // Get user ID
        if( $user_id > 0 ){
            $user = new WP_User($user_id);
            $user->remove_role('customer');
            $user->add_role('wholesale_customer');
        }
    }
}