Conditional checkout fields without plugin in WooCommerce

Last edited:
December 15, 2023
Reading time:
6 mins

/

Blog

/

WooCommerce

/

Conditional checkout fiel...

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

When it comes to checkout flow, providing a seamless and personalized experience is paramount. WooCommerce provides a complete and straight forward checkout process, making this whole experience quick and simple. However one crucial aspect of enhancing user experience is the ability to conditionally display checkout fields based on specific criteria. Unfortunately, this is not provided by default in WooCommerce.

Conditional checkout fields in WooCommerce checkout page

While several plugins offer this functionality, this guide will demonstrate how to implement conditional checkout fields in WooCommerce without relying on additional plugins. We’ll explore the importance of this customization, delve into the process of adding custom fields, and showcase how to implement conditional logic for a tailored checkout experience.

Why It’s Important

Enhancing User Experience

A streamlined and user-friendly checkout process contributes significantly to customer satisfaction. Conditional checkout fields allow you to gather relevant information from customers without overwhelming them with unnecessary form fields. By tailoring the checkout experience, you can create a more intuitive and efficient purchasing journey.

Gathering Relevant Data

For various products or services, you may need specific information from customers. Conditional fields enable you to collect data pertinent to the purchase, ensuring that your business has the necessary details for order fulfillment or customization.

Improving Checkout Flow

Excessive form fields can lead to cart abandonment. Conditional fields help declutter the checkout page, presenting customers with only the information relevant to their purchase. This simplification can enhance the overall flow of the checkout process.

Adding Custom Fields

Leveraging functions.php in a Child Theme

To begin, open the functions.php file of your child theme. Adding custom fields involves using actions and filters provided by WooCommerce.

Adding a Radio Button for Conditional Logic

We will introduce a radio button that serves as the trigger for conditional fields. This radio button will allow customers to indicate their preferences, triggering the display of relevant fields. We’ll utilize the woocommerce_form_field function to add the radio button.

Let’s start our coding 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="custom_checkout_field_cond_logic"><h2>' . __('Want an invoice;') . '</h2>';

    woocommerce_form_field( 'input_name_conditional', 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 Custom Fields Hidden/Shown Depending on the Radio Button

After adding our radio button, let’s add

add_action( 'woocommerce_after_order_notes', 'custom_conditional_checkout_fields', 901 );
function custom_conditional_checkout_fields( $checkout ) {
global $current_user;

    $companyname = get_user_meta($current_user->ID, 'company_name', true);
    echo '<div id="custom_checkout_field_company" style="display:none;">';

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

    echo '</div>';
	
    $companyid = get_user_meta($current_user->ID, 'company_vat', true);
    echo '<div id="custom_checkout_field_vat" style="display:none;">';

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

    echo '</div>';
}

Adding the Script for Conditional Logic

Using JavaScript and jQuery, you can control the visibility of custom fields based on the selected option of the radio button. This involves creating functions to hide or display fields dynamically. Ensure that your script is enqueued properly and only in your checkout page for performance reasons. The script should listen for changes to the radio button and adjust the visibility of associated fields accordingly.

<?php //do not copy this line

function custom_conditional_logic_checkout() {

if(is_checkout()){
 
?>

<script>
jQuery(document).ready(function($) {
    $("input[type='radio']").click(function() {
        var radioValue = $("input[name='input_name_conditional']:checked").val();
        var fieldsToToggle = ["custom_checkout_field_company", "custom_checkout_field_vat"];

        // Hide all fields by default
        fieldsToToggle.forEach(function(field) {
            $("#" + field).hide();
        });

        if (radioValue === "invoice") {
            // Display fields for invoice
            fieldsToToggle.forEach(function(field) {
                $("#" + field).show();
            });
        }
    });
});	
</script>

<?php
	}
}

add_action('wp_footer', 'custom_conditional_logic_checkout', 999);

Additional Considerations

How to save custom fields to order details

Now, let’s save the data to the order details so they are available through your order edit page:

// 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['input_name_conditional'] === 'invoice' ) {
                update_post_meta( $order_id, 'company_name', sanitize_text_field( $_POST['input_name_custom_company'] ) );
		update_post_meta( $order_id, 'company_vat', sanitize_text_field( $_POST['input_name_custom_vat'] ) );
    }
}

Validation and Error Handling:

Implement validation checks for custom fields to ensure that customers provide accurate information. Consider incorporating error messages and tooltips for better user guidance.

// 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['input_name_conditional'] === 'invoice' ) {
       if ( ! $_POST['input_name_custom_company'] )
        wc_add_notice( __( 'You have chosen invoice, please add company name.' ), 'error' );
	   if ( ! $_POST['input_name_custom_vat'] )
        wc_add_notice( __( 'You have chosen invoice, please add company VAT.' ), 'error' );

// apply other checks for your case	   

   }
}

Optimizing for Mobile Responsiveness:

Given the prevalence of mobile users, ensure that your conditional fields are optimized for various screen sizes. Test the checkout process on different devices to guarantee a seamless experience.

Testing Across Browsers:

Perform thorough testing across different web browsers to guarantee compatibility. Browser inconsistencies may arise, and preemptive testing can help identify and resolve issues.

Security Measures:

When collecting customer data, prioritize security. Ensure that your implementation aligns with data protection regulations and that sensitive information is handled securely.

An easy snippet for conditional checkout fields

Implementing conditional checkout fields in WooCommerce without plugins offers a tailored approach to collecting customer information. By understanding the importance of customization, adding custom fields judiciously, and incorporating conditional logic, you can optimize the checkout experience for your customers. Regular testing, security considerations, and ongoing optimization are key to maintaining a smooth and effective checkout process that aligns with your business objectives.