Home > Enterprise >  How to use WC_Order_Query class with custom order status
How to use WC_Order_Query class with custom order status

Time:02-10

There is a new order status I created: packed.

I want to get orders with order status "packed". This order status must have been created at least 2 days ago. However, I have a problem with time. date_modified is not working according to local time. Has anyone encountered this problem and has a solution?

$two_days_ago           = date(strtotime('-2 day'), current_time('timestamp'));
$current_time           = current_time('timestamp');
$args = array(
  'limit'           => -1,
  'return'          => 'ids',
  'date_modified '  => $two_days_ago_tomorrow.'...'.current_time('timestamp'),
  'status'          => 'a-packed'
);
$query = new WC_Order_Query( $args );

CodePudding user response:

wc_get_orders and WC_Order_Query provide a standard way of retrieving orders that is safe to use and will not break due to database changes in future WooCommerce versions. You pass in an array of arguments defining the criteria for the search.

More information: wc_get_orders and WC_Order_Query


Since you mention "This order status must have been created at least 2 days ago" in your question, it seems to me that the use of date_created is more suitable compared to date_modified

So you get:

$days_delay = 2; // 48 hours
$one_day    = 24 * 60 * 60;
$today      = strtotime( date('Y-m-d') );

$orders = wc_get_orders( array(
    'status'       => array( 'your-custom-status' ),
    'orderby'      => 'date',
    'order'        => 'ASC',
    'date_created' => '<' . ( $today - ( $days_delay * $one_day ) ),
));

foreach ( $orders as $order ) {
    $order_id = $order->get_id();
    echo '<p>' . $order_id . '</p>';
}
  • Related