Save checkout fields to user profile in WooCommerce

Last edited:
November 11, 2023
Reading time:
6 mins

/

Blog

/

WooCommerce

/

Save checkout fields to u...

đź’ˇWe may earn a commision if you subscribe to a service from a link on this page.

In the world of e-commerce, it’s essential to provide a seamless and personalized experience to your customers. One way to achieve this is by allowing customers to save specific checkout fields on their user profiles.

This feature is especially useful when you want to store data such as company details, tax information, or custom preferences for future orders. This means our example will be also using custom conditional checkout fields.

In this comprehensive guide, we’ll walk you through the process of saving checkout fields on user profiles in WooCommerce. We’ll provide you with the necessary code and instructions to implement this feature, including making these fields visible in order details and emails.

How It Benefits Your WooCommerce Store

Enhanced User Experience

By allowing customers to save their checkout fields on their user profiles, you enhance their shopping experience. This feature saves them time when they return to your store, as they don’t need to re-enter the same information with each purchase.

Data Accuracy

Storing data like company details, tax identification numbers, or custom preferences ensures the accuracy of the information. It reduces the chances of errors, which can be crucial for compliance and order fulfillment.

Improved Personalization

As you gather more data about your customers, you can personalize their shopping experience based on their preferences. For instance, you can tailor product recommendations or promotions to suit their needs.

Implementing the Feature

Using WooCommerce Hooks

We’ll implement this feature using WooCommerce hooks, which allow us to add fields to the checkout page, save the data to user profiles, and display it in order details and emails.

Let’s start by adding the field that is going to make are next fields conditional to the checkout page. For example, we can ask the customer if an invoice is needed and request further company information if invoice is chosen. Here’s how to add a simple radio button to the checkout page:


add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field', 900 );

function my_custom_checkout_field( $checkout ) {

    echo '<div  id="my_custom_checkout_field"><h2>' . __('Want an invoice;') . '</h2>';

    woocommerce_form_field( 'my_field_name', array(
        'type'          => 'radio',
        'class'         => array('my-field-class form-row-wide'),
        'label'         => __('Choose if you want a receipt or an invoice'),
		'default'         => 'receipt',
		'options'         => array(
        					'receipt'         => 'Receipt',
        					'invoice'    => 'Invoice',)
		
        ), $checkout->get_value( 'my_field_name' ));
	echo '</div>';
}

This code adds the “Choose if you want a receipt or an invoice” radio button to the checkout page.

Adding company fields in checkout page

Next step is to add the fields that will be visible after the user picks the invoice choice from the radio button above. Let’s add the company fields needed for invoicing:

add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field9', 901 );
function my_custom_checkout_field9( $checkout ) {
global $current_user;
$testvalue1 = get_user_meta($current_user->ID, 'company_name', true);
		
	echo '<div id="my_custom_checkout_field3" style="display:none;">';

    woocommerce_form_field( 'my_field_name3', array(
        'type'          => 'text',
        'class'         => array('my-field-class form-row-first'),
        'label'         => __('Company name'),
        'placeholder'   => __('Your company legal name'),
        ), $testvalue1);

    echo '</div>';
	$testvalue2 = get_user_meta($current_user->ID, 'company_activity', true);
	echo '<div id="my_custom_checkout_field4" style="display:none;">';

    woocommerce_form_field( 'my_field_name4', array(
        'type'          => 'text',
        'class'         => array('my-field-class form-row-last'),
        'label'         => __('Activity'),
        'placeholder'   => __('Your company business activity category'),
        ), $testvalue2);

    echo '</div>';
	$testvalue3 = get_user_meta($current_user->ID, 'company_vat_id', true);
    echo '<div id="my_custom_checkout_field5" style="display:none;">';

    woocommerce_form_field( 'my_field_name5', array(
        'type'          => 'text',
        'class'         => array('my-field-class form-row-first'),
        'label'         => __('VAT number'),
        'placeholder'   => __('Your company VAT number'),
        ), $testvalue3);

    echo '</div>';
	$testvalue4 = get_user_meta($current_user->ID, 'company_tax_office', true);
	echo '<div id="my_custom_checkout_field6" style="display:none;">';

    woocommerce_form_field( 'my_field_name6', array(
        'type'          => 'text',
        'class'         => array('my-field-class form-row-last'),
        'label'         => __('Tax office'),
        'placeholder'   => __('Your tax office ID/Name'),
        ), $testvalue4);


    echo '</div>';
}

The above code adds the necessary fields for getting the company details for an invoice. You can include additional fields by duplicating the woocommerce_form_field section with different field names, labels, and types.

Adding conditional logic to checkout fields

After adding all the fields to the checkout page, it’s time to add a little conditional logic with a small javascript snippet:

<?php //do not copy this line

function wpb_hook_javascript_checkout() {
 
?>

<script>
jQuery(document).ready(function( $ ) {
    jQuery(document).ready(function(){
        jQuery("input[type='radio']").click(function(){
            var radioValue = $("input[name='my_field_name']:checked").val();
            if(radioValue === "receipt"){
				
                var x = document.getElementById("my_custom_checkout_field3");
                x.style.display = "none";				
		var x = document.getElementById("my_custom_checkout_field4");
                x.style.display = "none";
		var x = document.getElementById("my_custom_checkout_field5");
                x.style.display = "none";
		var x = document.getElementById("my_custom_checkout_field6");
                x.style.display = "none";
				
            } else if(radioValue === "invoice"){
                var x = document.getElementById("my_custom_checkout_field3");
                x.style.display = "block";
		var x = document.getElementById("my_custom_checkout_field4");
                x.style.display = "block";
		var x = document.getElementById("my_custom_checkout_field5");
                x.style.display = "block";
		var x = document.getElementById("my_custom_checkout_field6");
                x.style.display = "block";
            }
        });
    });
});	
</script>

<?php
	
}

add_action('wp_footer', 'wpb_hook_javascript_checkout', 899);

With tha above code, all extra fields will be hidden. When a user selects the Invoice radio button, the fields will be visible and ready to be used.

Saving custom fields to user profiles (and order details)

Now, let’s save the data to user profiles, and of course the order details:

/**
 * Update the order meta with field value
 */
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );

function my_custom_checkout_field_update_order_meta( $order_id ) {
    if ( $_POST['my_field_name'] === 'invoice' ) {
         update_post_meta( $order_id, 'company_name', sanitize_text_field( $_POST['my_field_name3'] ) );
		update_post_meta( $order_id, 'company_activity', sanitize_text_field( $_POST['my_field_name4'] ) );
		update_post_meta( $order_id, 'company_vat_id', sanitize_text_field( $_POST['my_field_name5'] ) );
		update_post_meta( $order_id, 'company_tax_office', sanitize_text_field( $_POST['my_field_name6'] ) );
    }
}
add_action( 'woocommerce_checkout_order_processed', 'my_custom_checkout_field_update_after_order_profile_meta',  50  );
function my_custom_checkout_field_update_after_order_profile_meta( $order_id ) {
    if ( $_POST['my_field_name'] === 'invoice' ) {
          update_user_meta( get_current_user_id(), 'company_name', sanitize_text_field( $_POST['my_field_name3'] ) );
		update_user_meta( get_current_user_id(), 'company_activity', sanitize_text_field( $_POST['my_field_name4'] ) );
		update_user_meta( get_current_user_id(), 'company_vat_id', sanitize_text_field( $_POST['my_field_name5'] ) );
		update_user_meta( get_current_user_id(), 'company_tax_office', sanitize_text_field( $_POST['my_field_name6'] ) );
    }
}

/**
 * Process the checkout
 */
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

function my_custom_checkout_field_process() {
    // Check if set, if its not set add an error.
   if ( $_POST['my_field_name'] === 'invoice' ) {
       if ( ! $_POST['my_field_name3'] )
        wc_add_notice( __( 'You have chosen invoice, please add company name.' ), 'error' );
	   if ( ! $_POST['my_field_name4'] )
        wc_add_notice( __( 'You have chosen invoice, please add company VAT.' ), 'error' );
	   if ( ! $_POST['my_field_name5'] )
        wc_add_notice( __( 'You have chosen invoice, please add company activity.' ), 'error' );
	   if ( ! $_POST['my_field_name6'] )
        wc_add_notice( __( 'You have chosen invoice, please add company tax office.' ), 'error' );
   }
}

This code saves the Company fields data to the user’s profile, to the order details, and also validates the fields (so they are always filled when invoice is chosen). You can adapt it to save data for the any other fields you’ve added.

Displaying Fields in Account Page

To show these fields in order details and emails, you can use the following code:

/*
*/
add_action( 'edit_user_profile_update', 'save_company_details_kass' );
add_action( 'woocommerce_save_account_details', 'save_company_details_kass', 99 );

function save_company_details_kass( $user_id ) {
                update_user_meta( get_current_user_id(), 'company_name', sanitize_text_field( $_POST['my_field_name3'] ) );
		update_user_meta( get_current_user_id(), 'company_activity', sanitize_text_field( $_POST['my_field_name4'] ) );
		update_user_meta( get_current_user_id(), 'company_vat_id', sanitize_text_field( $_POST['my_field_name5'] ) );
		update_user_meta( get_current_user_id(), 'company_tax_office', sanitize_text_field( $_POST['my_field_name6'] ) );
}

add_action( 'woocommerce_edit_account_form', 'print_custom_account_fields', 4 );
    function print_custom_account_fields() {
		global $current_user;
		
		$testvalue1 = get_user_meta($current_user->ID, 'company_name', true);
    woocommerce_form_field( 'my_field_name3', array(
        'type'          => 'text',
        'class'         => array('woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide'),
        'label'         => __('Company name'),
        'placeholder'   => __('Your company legal name')
        ),
		$testvalue1);
		$testvalue2 = get_user_meta($current_user->ID, 'company_activity', true);
		woocommerce_form_field( 'my_field_name4', array(
        'type'          => 'text',
        'class'         => array('woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide'),
        'label'         => __('Activity'),
        'placeholder'   => __('Your company business activity category'),
        ),
		$testvalue2);
		
		$testvalue3 = get_user_meta($current_user->ID, 'company_vat_id', true);
		woocommerce_form_field( 'my_field_name5', array(
        'type'          => 'text',
        'class'         => array('woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide'),
        'label'         => __('VAT number'),
        'placeholder'   => __('Your company VAT number'),
        ),
		$testvalue3);
		
		$testvalue4 = get_user_meta($current_user->ID, 'company_tax_office', true);
		woocommerce_form_field( 'my_field_name6', array(
        'type'          => 'text',
        'class'         => array('woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide'),
        'label'         => __('Tax office'),
        'placeholder'   => __('Your tax office ID/Name'),
        ),
		$testvalue4);
}

This code displays the fields in the account page.

Displaying Fields in Order Details and Emails

To show these fields in order details and emails, you can use the following code:

/**
 * Display field value on the order edit page
 */
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );

function my_custom_checkout_field_display_admin_order_meta($order){
    echo '<p><strong>'.__('company_name').':</strong> ' . $order->get_meta('company_name') . '</p>';
	echo '<p><strong>'.__('company_activity').':</strong> ' . $order->get_meta('company_activity') . '</p>';
	echo '<p><strong>'.__('company_vat_id').':</strong> ' . $order->get_meta('company_vat_id') . '</p>';
	echo '<p><strong>'.__('company_tax_office').':</strong> ' . $order->get_meta('company_tax_office') . '</p>';
}

This code displays the “Company Name” field in the WooCommerce admin order details. You can extend it to show other fields as needed.

Conclusion

Enabling customers to save checkout fields on their user profiles in WooCommerce is a valuable feature that enhances user experience, ensures data accuracy, and enables personalized marketing. By using WooCommerce hooks, you can easily add, save, and display these fields, tailoring the shopping experience for your customers and simplifying the process for returning visitors. It’s a win-win solution for both you and your customers, fostering better relationships and increasing your e-commerce success.

Leave a Reply

Your email address will not be published. Required fields are marked *