有没有办法通过WooCommerce API获得顶级销售产品?

I have tried to get list of top sales product by Woocommerce API, I'm using version 1 of WooCommerce API. I tried this following endpont, but it does not work:

My Request:

https://DOMAINNAME.com/wp-json/wc/v1/products?consumer_key=CONSUMER_KEY&consumer_secret=CONSUMER_SECRET&category=CATEGORY_ID&order=asc&orderby=total_sales

But it Responses:

{
    "code": "rest_invalid_param",
    "message": "Invalid parameter(s): orderby",
    "data": {
        "status": 400,
        "params": {
            "orderby": "orderby is not one of date, id, include, title, slug."
        }
    }
}

orderby is not one of date, id, include, title, slug. So, I can order by date, ID, include, title and slug only. How can I order by total_sales . Is it possible to do? Or can you suggest any other way?

You'll need to add a REST API filter via functions.php in your theme (or a plugin file) in order to make sure that meta_key and meta_value are allowed to be used.


add_filter('rest_endpoints', function ($routes) {
    // I'm modifying multiple types here, you won't need the loop if you're just doing WooCommerce products
    foreach (['product', 'another_type'] as $type) {
        if (!($route =& $routes['/wp/v2/' . $type])) {
            continue;
        }

        // Allow ordering by my meta value
        $route[0]['args']['orderby']['enum'][] = 'meta_value_num';

        // Allow only the meta keys that I want
        $route[0]['args']['meta_key'] = array(
            'description'       => 'The meta key to query.',
            'type'              => 'string',
            'enum'              => ['my_meta_key', 'another_key'],
            'validate_callback' => 'rest_validate_request_arg',
        );
    }

return $routes;
});

you can add any meta keys you'd like added to the enum values. Doing it this way (instead of adding a filter to add endpoints for all meta_key) keeps potentially sensitive information saved as metadata from being publicly readable.

Then, try this for your URL:

https://DOMAINNAME.com/wp-json/wc/v1/products?consumer_key=CONSUMER_KEY&consumer_secret=CONSUMER_SECRET&category=CATEGORY_ID&order=asc&filter[meta_key]=total_sales&orderby=meta_value_num