duanfei9278 2018-03-24 05:42
浏览 91

有没有办法通过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?

  • 写回答

1条回答 默认 最新

  • doudian7996 2018-03-24 06:44
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line