Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Add Delivery Date Field Below Shipping Methods in WooCommerce Cart and Checkout page?

Allowing customers to pick a delivery date on the WooCommerce checkout page is a valuable addition your store should go with to increase customer satisfaction. WooCommerce gives you a lot of control over every aspect of customizing your online store. You can easily add a custom field on the WooCommerce checkout page.

This post helps you to add a delivery date field below shipping methods in the WooCommerce cart and checkout page.

Where to Add Custom Code in WooCommerce?

It is advisable to add the code snippets to the functions.php file of your child theme. Access the file directly from Appearance->Theme File Editor->Locating the child theme’s functions.php from the right sidebar. You can also access it from your theme’s directory file. Insert the following code snippet in functions.php. The alternative & easy option is to install & activate the Code Snippets plugin. You can then add the code as a new snippet via the plugin.

Preliminary Steps

Decide the shipping method you wish to place the delivery date field and find its ID. You can do this by going to the WooCommerce checkout page, then right-click on the Shipping method->Select Inspect->Developer tools. The Free shipping method ID, in this case, is flat_rate:25.

How to Add Delivery Date Field Below Shipping Methods in WooCommerce Cart and Checkout page? - Tyche Softwares

Solution: Add Delivery Date Field Below Shipping Methods in WooCommerce Cart and Checkout

Imagine an online store selling fresh products such as fruits, vegetables, and dairy products. The code snippet helps the store to show a delivery date field on the cart and checkout page. In such cases, customers will be able to choose their preferred delivery date and receive fresh produce just when they need it. 

Delivery Date Settings Function
// Custom function that handles your settings
function ts_delivery_date_settings(){
    return array(
        'targeted_methods' => array('flat_rate:25'), // Define your targeted shipping method(s)
        'field_id'         => 'delivery_date', // Field Id
        'field_type'       => 'date', // Field type (date input)
        'label_name'       => __("Delivery Date","woocommerce"), // Label name for validation and as meta key for orders
    );
}
Display Custom Delivery Date Field
// Display the custom delivery date field
add_action( 'woocommerce_after_shipping_rate', 'ts_delivery_date_custom_date_field', 20, 2 );
function ts_delivery_date_custom_date_field( $method, $index ) {
    extract( ts_delivery_date_settings() ); // Load settings and convert them into variables
    // Get the chosen shipping methods
    $chosen = WC()->session->get('chosen_shipping_methods');
    $value = WC()->session->get($field_id);
    $value = WC()->session->__isset($field_id) ? $value : WC()->checkout->get_value('_'.$field_id);
    if( ! empty($chosen) && $method->id === $chosen[$index] && in_array($method->id, $targeted_methods) ) {
        echo '<div class="custom-delivery-date">';
        woocommerce_form_field( $field_id, array(
            'type'     => $field_type,
            'label'    => '', // Not required for date input
            'class'    => array('form-row-wide ' . $field_id . '-' . $field_type ),
            'required' => true,
        ), $value );
        echo '</div>';
    }
}
Save the Delivery Date to Order
// Save the delivery date to order
add_action('woocommerce_checkout_create_order', 'ts_save_delivery_date_to_order');
function ts_save_delivery_date_to_order($order) {
    $field_id = 'delivery_date';
    if (isset($_POST[$field_id])) {
        $order->update_meta_data('_'.$field_id, sanitize_text_field($_POST[$field_id]));
    }
}
Display Delivery Date in Admin Orders
// Display the delivery date in admin orders
add_filter('woocommerce_admin_order_data_after_billing_address', 'ts_display_delivery_date_in_admin_orders');
function ts_display_delivery_date_in_admin_orders($order) {
    $field_id = 'delivery_date';
    $value = $order->get_meta('_'.$field_id);
    if ($value) {
        echo '<p><strong>'.__('Delivery Date').':</strong> ' . esc_html($value) . '</p>';
    }
}
Send Delivery Date via AJAX to WordPress Backend
// jQuery code (client side) - Ajax sender
add_action( 'wp_footer', 'ts_delivery_date_script_js' );
function ts_delivery_date_script_js() {
    // Only cart & checkout pages
    if( is_cart() || ( is_checkout() && ! is_wc_endpoint_url() ) ):
    // Load settings and convert them into variables
    extract( ts_delivery_date_settings() );
    $js_variable = is_cart() ? 'wc_cart_params' : 'wc_checkout_params';
    // jQuery Ajax code
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof <?php echo $js_variable; ?> === 'undefined')
            return false;
        $(document.body).on( 'change', 'input#<?php echo $field_id; ?>', function(){
            var value = $(this).val();
            $.ajax({
                type: 'POST',
                url: <?php echo $js_variable; ?>.ajax_url,
                data: {
                    'action': 'delivery_date',
                    'value': value
                },
                success: function (result) {
                    console.log(result); // Only for testing (to be removed)
                }
            });
        });
    });
    </script>
    <?php
    endif;
}
WordPress AJAX PHP Receiver
// The WordPress Ajax PHP receiver
add_action( 'wp_ajax_delivery_date', 'ts_set_delivery_date' );
add_action( 'wp_ajax_nopriv_delivery_date', 'ts_set_delivery_date' );
function ts_set_delivery_date() {
    if ( isset($_POST['value']) ){
        // Load settings and convert them into variables
        extract( ts_delivery_date_settings() );
        $value = sanitize_text_field( $_POST['value'] );
        // Update session variable
        WC()->session->set( $field_id, $value );
        // Send back the data to JavaScript (JSON encoded)
        echo $value;
        die();
    }
}
Display the Delivery Date on the Thank-You Page
// Display the delivery date on the thank-you page
add_action('woocommerce_thankyou', 'ts_display_delivery_date_on_thankyou', 10, 1);
function ts_display_delivery_date_on_thankyou($order_id) {
    // Retrieve the delivery date from order metadata
    $delivery_date = get_post_meta($order_id, '_delivery_date', true);
    // Display the delivery date if it exists
    if ($delivery_date) {
        echo '<p><strong>Delivery Date:</strong> ' . esc_html($delivery_date) . '</p>';
    }
}




Output

Cart Page

The output displays the date field option within the Flat rate shippping method, allowing customers to choose their preferred delivery date on the cart page.

How to Add Delivery Date Field Below Shipping Methods in WooCommerce Cart and Checkout page?

Checkout page

The output displays the date field option within the Flat rate shippping method, allowing customers to choose their preferred delivery date on the checkout page.

How to Add Delivery Date Field Below Shipping Methods in WooCommerce Cart and Checkout page?

Order Received page

The output shows us that on the Order Received page, customer-chosen delivery date details will be displayed.

Order Received page

Admin section

The following output shows the admin section where the delivery date choosen by the customer is retrieved.

Admin section
How to Add Delivery Date Field Below Shipping Methods in WooCommerce Cart and Checkout page? - Tyche Softwares

Schedule Local Deliveries & Pickups in WooCommerce

Order Delivery Date Pro for WooCommerce lets you create different delivery schedules, set charges for Weekdays & special dates, manage local pickup dates, and notify customers once the order is ready

Since the customers pick a delivery date and time set by you, order fulfillment and customer satisfaction becomes a breeze.

Code Explanation

1. Delivery Date Settings Function

  • This function, named ts_delivery_date_settings(), is used to define various configuration settings for the delivery date feature. Here’s what each setting means:
    • ‘targeted_methods’: This specifies which shipping methods should have the delivery date field. In this case, it’s set to array(‘flat_rate:25’), meaning that the field will appear for the ‘flat_rate’ shipping method with an ID of ’25’.
    • ‘field_id’: This is the unique identifier for the delivery date field, set to ‘delivery_date’.
    • ‘field_type’: It defines the type of input field, and it’s set to ‘date’, indicating a date picker input.
    • ‘label_name’: This is the label displayed next to the date input, and it’s set to ‘Delivery Date’ for the WooCommerce plugin.

2. Display Custom Delivery Date Field

  • This section uses the add_action function to hook into WooCommerce’s woocommerce_after_shipping_rate action, which is triggered after shipping rates are displayed during checkout.
  • The ts_delivery_date_custom_date_field function is defined to handle the display of the custom delivery date field.
  • It first extracts the settings defined in the ts_delivery_date_settings() function.
  • It then checks whether the selected shipping method matches the targeted method (e.g., ‘flat_rate:25’) and whether the delivery date field should be displayed.
  • If conditions are met, it prints HTML code for the date input field with the specified settings.

3. Save Delivery Date to Order

  • Here, an action hook is used to add a function called ts_save_delivery_date_to_order to the woocommerce_checkout_create_order action.
  • The ts_save_delivery_date_to_order function checks if the delivery date has been provided in the checkout form data ($_POST).
  • If a date is provided, it sanitizes the input to make it safe and updates the order’s metadata with the sanitized delivery date.

4. Display Delivery Date in Admin Orders

  • This section adds a filter hook to woocommerce_admin_order_data_after_billing_address to display the delivery date in admin orders.
  • The ts_display_delivery_date_in_admin_orders function retrieves the delivery date from the order’s metadata and displays it in the admin order details if it exists.

5. Send Delivery Date via AJAX to WordPress Backend

  • This part of the code adds client-side functionality using jQuery to enhance the customer’s interaction with the delivery date field. Here’s what it does:
    • It checks if the current page is the cart page or the checkout page (excluding WooCommerce endpoints).
    • It extracts the delivery date settings for client-side use.
    • It sets up a jQuery event listener to detect changes in the delivery date input field.
    • When the date changes, it sends an AJAX POST request to the server with the new date value.
    • It also includes a snippet to retrieve and display a previously selected date from local storage when the page loads.

6. WordPress AJAX PHP Receiver

  • This section sets up the server-side handling of AJAX requests initiated by the client-side code.
  • Two action hooks are used to define PHP functions, ts_set_delivery_date, and ts_set_delivery_date for handling AJAX requests with and without user authentication.
  • The ts_set_delivery_date function retrieves the new delivery date value from the AJAX request, updates the session variable with the new value, and sends the value back to the client-side JavaScript in JSON format.

7. Display the delivery date on the thank-you page

  • The code uses the add_action function to attach a custom function, display_delivery_date_on_thankyou, to the woocommerce_thankyou action.
  • The display_delivery_date_on_thankyou function is defined to handle the display of the delivery date on the thank-you page.
  • Inside the function, the code utilizes the get_post_meta function to retrieve the delivery date associated with the order. The order ID is used as a reference to access order-specific information. The retrieved delivery date is stored in the $delivery_date variable.
  • The code then proceeds to check if a delivery date exists by using an if statement. If a delivery date is found (i.e., not empty or false), the following steps are executed.
  • When a delivery date exists, it is dynamically displayed on the thank-you page. This is achieved by echoing HTML code that includes a paragraph (<p>) element with the label “Delivery Date” in bold (<strong>). The actual delivery date, sanitized and escaped using the esc_html function to ensure security and proper rendering in HTML, is also included in this HTML output.

How to add a delivery date field via plugin

If you want to add the same functionality via a plugin, then you can use our Order Delivery Date Pro plugin for WooCommerce. This plugin lets you create different delivery schedules, set charges for Weekdays & special dates, manage local pickup dates, notify customers once the order is ready, and real-time syncing of your deliveries with Google Calendar. Look into the frontend image of this plugin given below.

Order Delivery Date Pro Plugin Frontend

How to add a delivery date field via plugin

Conclusion

The above code helps you to add a delivery date field on the WooCommerce cart and checkout page.

Let us know how the code was useful or any other queries in the comments section.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It: