WooCommerce: Get date when order was cancelled

I am trying to get the date when an order was marked as Status: “Cancelled”.

My current approach involves getting all order notes using wc_get_order_notes().

Any better approach to get this information?

function get_cancellation_date_with_timezone($order_id) {
    $order = wc_get_order($order_id);

    if (!$order) {
        return false; // Order not found
    }

    // Retrieve all order notes
    $notes = wc_get_order_notes(array('order_id' => $order_id));

    foreach ($notes as $note) {
        // Check if the note indicates a status change to 'Cancelled'
        if (strpos($note->content, 'Order status changed from') !== false && strpos($note->content, 'to Cancelled') !== false) {
            // Get the date created and timezone
            $date_created = $note->date_created;
            $timezone = new DateTimeZone($date_created->getTimezone()->getName());

            // Create a DateTime object with timezone
            $date = new DateTime($date_created->date('Y-m-d H:i:s'), $timezone);

            // Format the date with timezone
            return $date;
        }
    }

    return false; // Cancellation note not found
}

$cancellation_date = get_cancellation_date_with_timezone($order_id = 1234);
echo $cancellation_date->format('Y-m-d\TH:i:sP');

Improving the get_cancellation_date_with_timezone Function

Direct Status Check:

Instead of parsing the note content, directly check the order’s current status using $order->get_status(). This is more efficient and reliable:

PHP

function get_cancellation_date_with_timezone($order_id) {
    $order = wc_get_order($order_id);

    if (!$order) {
        return false; // Order not found    1.  stackoverflow.com stackoverflow.com
    }

    if ($order->get_status() === 'cancelled') {
        $date_created = $order->get_date_created();
        $timezone = new DateTimeZone($date_created->getTimezone()->getName());
        $date = new DateTime($date_created->date('Y-m-d H:i:s'), $timezone);
        return $date;
    }

    return false; // Order is not cancelled
}

Additional Considerations:

  • Multiple Status Changes: If an order can change its status multiple times, you might need to track the cancellation date more precisely. Consider storing a custom field or meta value to indicate the exact cancellation timestamp.
  • Order Notes for Other Purposes: If you still need to parse order notes for other information, you can use a more specific search criteria or regular expression to match the cancellation event.
  • Performance Optimization: For large numbers of orders, consider caching the cancellation date or using a database query to directly retrieve it if you have a custom field or meta value.

By using the direct status check and considering these additional factors, you can improve the efficiency and accuracy of your get_cancellation_date_with_timezone function.