How to create WordPress custom end point with multiple parameters?

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/(?Pstart_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-01end_date=2021-09-30

Topic wp-api plugin-json-api rest-api plugin-development plugins Wordpress

Category Web


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' );
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.