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

How to Add a Custom Date Range Input Field To WooCommerce Product Page?

It is common to have a product delivery date as an input field for booking-related products. But when customers are confused about when exactly they want their products to be delivered, a simple date field doesn’t serve the need. For example, if customers want a specific piece of furniture delivered after completing housework, they can choose a broader timeframe instead of an exact date.

Luckily, with a simple snippet you can easily integrate this product delivery date range field on the WooCommerce product page. Let’s dive in to know how it works!

Solution: Add a Custom Date Range Input Field To WooCommerce Product Page

This code snippet will add a custom date range fields on the specific product page and ensures that this information is displayed accurately throughout the ordering process.

// Add custom date range to product page
add_action( 'woocommerce_before_add_to_cart_button', 'ts_display_custom_date_range_picker', 9 );
function ts_display_custom_date_range_picker() {
    echo '<div class="custom-date-range-picker">';
    // Custom Date From Field
    woocommerce_form_field( 'custom_date_from', array(
        'type'         => 'date',
        'required'     => false, // Change to true if field is required
        'label'        => 'Custom Date From',
        'placeholder'  => 'Select custom date...',
        'class'        => array('custom-date-picker-class'), // Add custom CSS class if needed
        'autocomplete' => 'off', // Disable browser autocomplete
    ));
    // Custom Date To Field
    woocommerce_form_field( 'custom_date_to', array(
        'type'         => 'date',
        'required'     => false, // Change to true if field is required
        'label'        => 'Custom Date To',
        'placeholder'  => 'Select custom date...',
        'class'        => array('custom-date-picker-class'), // Add custom CSS class if needed
        'autocomplete' => 'off', // Disable browser autocomplete
    ));
    echo '</div>';
}

// Save Custom Product Fields values
add_filter( 'woocommerce_add_cart_item_data', 'ts_save_custom_product_fields_values', 10, 2 );
function ts_save_custom_product_fields_values( $cart_item_data, $product_id ) {
    if ( isset( $_POST['custom_date_from'] ) && isset( $_POST['custom_date_to'] ) ) {
        $cart_item_data['custom_date_from'] = sanitize_text_field( $_POST['custom_date_from'] );
        $cart_item_data['custom_date_to']   = sanitize_text_field( $_POST['custom_date_to'] );
    }
    return $cart_item_data;
}

// Display custom date range in cart and checkout
add_filter( 'woocommerce_get_item_data', 'ts_display_custom_date_range_in_cart_checkout', 10, 2 );
function ts_display_custom_date_range_in_cart_checkout( $cart_data, $cart_item ) {
    if ( isset( $cart_item['custom_date_from'] ) && isset( $cart_item['custom_date_to'] ) ) {
        $cart_data[] = array(
            'key'   => 'Custom Date Range',
            'value' => sprintf( 'From %s to %s', $cart_item['custom_date_from'], $cart_item['custom_date_to'] ),
        );
    }
    return $cart_data;
}

// Save the custom date range to the order items
add_action( 'woocommerce_checkout_create_order_line_item', 'ts_save_custom_date_range_to_order_items', 10, 4 );
function ts_save_custom_date_range_to_order_items( $item, $cart_item_key, $values, $order ) {
    $custom_date_from = isset( $values['custom_date_from'] ) ? $values['custom_date_from'] : '';
    $custom_date_to   = isset( $values['custom_date_to'] ) ? $values['custom_date_to'] : '';

    if ( ! empty( $custom_date_from ) && ! empty( $custom_date_to ) ) {
        $item->add_meta_data( 'Custom Date Range', sprintf( 'From %s to %s', $custom_date_from, $custom_date_to ) );
    }
}

// Display custom date range in order details page
add_action( 'woocommerce_order_item_meta_end', 'ts_display_custom_date_range_in_order_details', 10, 3 );
function ts_display_custom_date_range_in_order_details( $item_id, $item, $order ) {
    $custom_date_range = $item->get_meta( 'Custom Date Range', true );
    if ( ! empty( $custom_date_range ) ) {
        echo '<br><small>Custom Date Range: ' . $custom_date_range . '</small>';
    }
}

// Display custom date range in admin order items table
add_filter( 'woocommerce_order_item_name', 'ts_display_custom_date_range_in_admin_order_items_table', 10, 2 );
function ts_display_custom_date_range_in_admin_order_items_table( $item_name, $item ) {
    $custom_date_range = $item->get_meta( 'Custom Date Range', true );
    if ( ! empty( $custom_date_range ) ) {
        $item_name .= '<br><small>Custom Date Range: ' . $custom_date_range . '</small>';
    }
    return $item_name;
}

Output

When a customer visits the product page, they will be presented with a custom date range picker, allowing them to select a start and end date for product delivery. The selected date range is displayed on the cart, checkout, and in the order items table.

How to Add a Custom Date Range Input Field To WooCommerce Product Page? - Tyche Softwares

The customer selected date range values gets saved and displayed in the checkout page as well.

How to Add a Custom Date Range Input Field To WooCommerce Product Page? - Tyche Softwares

Solution: Restrict Booking Dates Based on Product Attribute Values in WooCommerce

When offering booking products in WooCommerce, you might need to restrict the available dates for selection based on a specific deadline. For example, if a product requires a booking deadline of three days in advance, customers should only be able to select dates beyond this limit.

Let’s create a product attribute called Booking Deadline (Days) with values of 3, 5, and 7 days, as shown below.

How to Add a Custom Date Range Input Field To WooCommerce Product Page? - Tyche Softwares

// Enqueue jQuery UI Datepicker
add_action('wp_enqueue_scripts', 'ts_enqueue_jquery_ui');
function ts_enqueue_jquery_ui() {
    if (is_product()) {
        wp_enqueue_script('jquery-ui-datepicker');
        wp_enqueue_style('jquery-ui-style', 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css');
    }
}

// Add Custom Date Fields to WooCommerce Product Page
add_action('woocommerce_before_add_to_cart_button', 'ts_display_custom_date_picker', 9);
function ts_display_custom_date_picker() {
    global $product;

    // Retrieve "Booking Deadline (Days)" from product attributes
    $attributes = $product->get_attributes();
    $booking_deadline_days = isset($attributes['booking_deadline_days']) ? intval($attributes['booking_deadline_days']) : 0;

    // Hidden input to store Booking Deadline Days
    echo '<input type="hidden" id="booking-deadline-days" value="' . esc_attr($booking_deadline_days) . '">';

    echo '<div class="custom-date-picker-container" style="max-width: 300px;">';

    // Custom Date From Field
    woocommerce_form_field('custom_date_from', array(
        'type'        => 'text',
        'required'    => true,
        'label'       => 'Custom Date From',
        'placeholder' => 'mm/dd/yyyy',
        'class'       => array('custom-date-picker'),
        'autocomplete' => 'off',
    ));

    // Custom Date To Field
    woocommerce_form_field('custom_date_to', array(
        'type'        => 'text',
        'required'    => true,
        'label'       => 'Custom Date To',
        'placeholder' => 'mm/dd/yyyy',
        'class'       => array('custom-date-picker'),
        'autocomplete' => 'off',
    ));

    echo '</div>';
}
// Save Custom Date Fields to Cart Item Data
add_filter('woocommerce_add_cart_item_data', 'ts_save_custom_dates_to_cart', 10, 2);
function ts_save_custom_dates_to_cart($cart_item_data, $product_id) {
    if (isset($_POST['custom_date_from']) && isset($_POST['custom_date_to'])) {
        $cart_item_data['custom_date_from'] = sanitize_text_field($_POST['custom_date_from']);
        $cart_item_data['custom_date_to'] = sanitize_text_field($_POST['custom_date_to']);
    }
    return $cart_item_data;
}

// Display Custom Date Fields in Cart
add_filter('woocommerce_get_item_data', 'ts_display_custom_dates_in_cart', 10, 2);
function ts_display_custom_dates_in_cart($item_data, $cart_item) {
    if (!empty($cart_item['custom_date_from']) && !empty($cart_item['custom_date_to'])) {
        $item_data[] = array(
            'name' => 'Booking Dates',
            'value' => esc_html($cart_item['custom_date_from'] . ' - ' . $cart_item['custom_date_to'])
        );
    }
    return $item_data;
}

// Dynamic Date Blocking 
add_action('wp_footer', 'ts_enqueue_datepicker_script');
function ts_enqueue_datepicker_script() {
    if (is_product()) {
        ?>
        <script>
            jQuery(document).ready(function($) {
                if (typeof $.fn.datepicker !== "function") {
                    console.log("Error: jQuery UI Datepicker not loaded.");
                    return;
                }

                function updateDatepicker() {
                    var bookingDeadlineDays = parseInt($('#booking-deadline-days').val()) || 0;
                    var minDate = new Date();
                    minDate.setDate(minDate.getDate() + bookingDeadlineDays);

                    // Reinitialize the datepickers with updated minDate
                    $('#custom_date_from, #custom_date_to').datepicker("destroy").datepicker({
                        dateFormat: 'mm/dd/yy',
                        minDate: minDate,
                        changeMonth: true,
                        changeYear: true,
                        showAnim: "fadeIn"
                    }).css("width", "100%").attr('readonly', true);
                }

                // Run initially
                updateDatepicker();

                // Listen for Booking Deadline Days change (if applicable)
                $('#booking-deadline-days').on('change', function() {
                    updateDatepicker();
                });

                // Prevent manual input
                $('#custom_date_from, #custom_date_to').on('keydown', function(e) {
                    e.preventDefault();
                    return false;
                });
            });
        </script>
        <?php
    }
}

Let’s consider a customer who visits a WooCommerce product page that has a booking deadline set (e.g., 3 , 5 , and 7 days).

How to Add a Custom Date Range Input Field To WooCommerce Product Page? - Tyche Softwares

Let’s consider a scenario where a customer visits a WooCommerce product page and with a Booking Deadline (Days) attribute set to 3, 5, or 7 days. Suppose today’s date is March 18th.

  • If the booking deadline is set to 3 days, customers cannot select past dates or the next three days (March 18, 19, and 20). The earliest selectable date will be March 21st.
  • Similarly, if the booking deadline is set to 5 days, the first available date will be March 23rd.
  • For a 7-day booking deadline, the datepicker will only allow selections starting from March 25th.

This means that the available dates start from today’s date + Booking Deadline (Days).

Look into the demonstration video below to get a better understanding on how the booking deadline days are blocked. 

The above feature is especially useful for businesses like hotels, rentals, and event organizers that need time to arrange resources before a booking. With our Booking and Appointment Plugin for WooCommerce, you can easily configure Booking Deadline Days to match your business needs. Whether you want to prevent last-minute rush bookings based on date or time slot or any other booking-related feature can be set up easily in just a few clicks.

This customization allows customers to enter their preferred date range. Alternatively, as an admin, if you want to let customers know the date range when you can deliver products, you need to add product date range input fields on the product editor page in the admin backend. The entered date range will be visible on the product page, letting customers know the date range when the product is available for booking.

Browse more in: Code Snippets, WooCommerce How Tos

Share It:

Subscribe
Notify of
0 Comments
Newest
Oldest
Inline Feedbacks
View all comments
3 months ago

The woocommerce_form_field
‘required’ => true,
does not work as expected.


2 months ago
Reply to  Saranya

Hi Saranya

Thank you for getting back to me with this handy solution. It works perfect!

Another useful improvement would be to block selecting passed dates. In my case, I have a global product attribute, called Booking Deadline (Days). How to implement this in the date picker, to block current date + Booking Deadline (Days) for all products?

Thank you again for your prompt reply.

Cheers
Alvin

0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible.

Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

By using our site, you acknowledge that you have read and understood our Privacy Policy and Terms & Conditions.