0

I want to get all WooCommerce orders from given date range. I can retrieve all orders at once. But I am confusing with passing the date range via API URL.

Can anybody help me with this? I know it's something like this but can't figure out the exact way to do it.

Here is my route:

add_action('rest_api_init', function() {
    register_rest_route('woo/v2', 'woocommerce/order_summary_by_date/(?P<start_date>/<end_date>)', array(
        'methods' => 'GET',
        'callback' => 'woocommerce_orders_by_dates'
    ));
});

This is function to access:

function woocommerce_orders_by_dates($start_date, $end_date) {
    $start_date = $start_date['start_date'];
    $end_date = $end_date['start_date'];

    return $start_date . $end_date;
}

URL is: https://example.com/wp-json/woo/v2/woocommerce/order_summary_by_date/?start_date=2021-09-01&end_date=2021-09-30

1 Answer 1

2

When you register a route, parameters accepted via the query string (eg. ?a=b&c=d) are not registered as part of the endpoint, like you have done. Those parameters just need to be defined in the args property:

add_action(
    'rest_api_init',
    function() {
        register_rest_route(
            'woo/v2',
            'woocommerce/order_summary_by_date',
            array(
                'methods'  => 'GET',
                'callback' => 'woocommerce_orders_by_dates'
                'args'     => array(
                    'start_date' => array(
                        'required' => true,
                    ),
                    'end_date'   => array(
                        'required' => true,
                    ),
                ),
            )
        );
    }
);

You can also defined sanitization and validation callbacks for the arguments. This is all described in the documentation.

To access the values you use the $request object passed to the callback:

function woocommerce_orders_by_dates( $request ) {
    $start_date = $request->get_param( 'start_date' );
    $end_date   = $request->get_param( 'end_date' );
}
1
  • Thank you very much. Sep 3, 2021 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.