Ad

Query WooCommerce Orders Within A Date Range Through A Custom Meta Key

I have a meta_key called delivered_date, in date format, example 2021-05-13 16:01:26.

If I MUST use wc_get_orders( $args ), how can I get all orders within a date range?

Tried using the meta_compare argument but it returns nothing:

// The 2 variables below will come from a datepicker widget
$start_date = "2021-05-10 0:00:00";
$end_date = "2021-05-30 11:59:59";

$args = array(
        'type'         => 'shop_order',
        'limit'        => 100,
        'paginate'     => true,
        'page'         => 1,
        'orderby'      => 'id',
        'order'        => 'DESC',
        'meta_key'     => 'delivered_date',
        'meta_value'   => array($start_date, $end_date),
        'meta_compare' => 'BETWEEN',
    );

$result = wc_get_orders( $args );
Ad

Answer

You are close, use date — Format a local time/date

So you get:

// The 2 variables below will come from a datepicker widget
$start_date = date( '2021-05-10 00:00:00' );
$end_date = date( '2021-05-30 11:59:59' );

$args = array(
    'orderby'      => 'id',
    'order'        => 'DESC',
    'meta_key'     => 'delivered_date',
    'meta_value'   => array( $start_date, $end_date ),
    'meta_compare' => 'BETWEEN',
);

$orders = wc_get_orders( $args );

// NOT empty
if ( ! empty ( $orders ) ) {        
    foreach ( $orders as $order ) {         
        echo '<p>ID = ' . $order->get_id() . '</p>';
    }
}

Result: ID = 2525, ID = 2524, ID = 2523

enter image description here

Ad
source: stackoverflow.com
Ad