I need to get orders only if order was created from given date, let's say: 01/11/2024. Then I would get order created from the day 01/11/2024 to the actual date (today).
I found this code which does something similar fetching orders within the last 24h only. I guess I need to convert my date to timestamp like:
$myDate = '2024/11/01';
$timestamp = strtotime($myDate);
But I can not figure out how to integrate/modify:
$order = wc_get_order( $customer_order );
$date_created_dt = $order->get_date_completed();
$timezone = $date_created_dt->getTimezone(); // Get the timezone
$date_created_ts = $date_created_dt->getTimestamp(); // Get the timestamp in seconds
$now_dt = new WC_DateTime(); // Get current WC_DateTime object instance
$now_dt->setTimezone( $timezone ); // Set the same time zone
$now_ts = $now_dt->getTimestamp(); // Get the current timestamp in seconds
$twenty_four_hours = 24 * 60 * 60; // 24hours in seconds
$diff_in_seconds = $now_ts - $date_created_ts; // Get the difference (in seconds)
// Output
if ( $diff_in_seconds < $twenty_four_hours ) {
echo '<p>Order created LESS than 24 hours ago</p>';
}
To get all orders starting from a given date, you can use a query compatible with High-Performance Order Storage (HPOS) using wc_get_orders()
function with date_created
argument as follows:
$start_date = '2024/11/01';
$start_date_obj = new WC_DateTime($start_date); // Get the WC_DateTime object
$start_date_obj->setTimezone( wp_timezone() ); // Set WordPress timezone
// Query all orders starting from the defined date
$orders = wc_get_orders( array(
'limit' => -1,
'date_created' => '>=' . $start_date_obj->date( 'Y-m-d H:i:s' ) ),
) );
// Loop through orders starting from the given date
foreach ( $orders as $order ) {
// Do something
}
For the timezone: Using WordPress wp_timezone()
is much more simpler.
Other useful WC_Order_Query arguments:
The order statuses to query using 'status'
,
The user ID to target using 'customer'
,
The date type: 'date_created'
, 'date_modified'
, 'date_completed'
or 'date_paid'
.
See wc_get_orders and WC_Order_Query developer dodumentation
To filter an order from a given start date, we start using a similar code:
$start_date = '2024/11/01';
$start_date_obj = new WC_DateTime($start_date); // Get the WC_DateTime object
$start_date_obj->setTimezone( wp_timezone() ); // Set WordPress timezone
$order = wc_get_order( $order_id ); // Get the WC_Order object form the ID
$order_date = $order->get_date_created(); // Get order creation date object
// Dates timestamp comparision
if ( $order_date->getTimestamp() >= $start_date_obj->getTimestamp() ) {
// Output something
printf( '<p>Order created after %s start date.</p>', $start_date );
}
See WC_DateTime
Class and methods and native PHP DateTime
Class and methods.