我试图通过WooCommerceAPI获得最畅销的产品列表,我使用的是WooCommerceAPI的第1版。我尝试了以下endpont,但不起作用:
我的请求:
https://DOMAINNAME.com/wp-json/wc/v1/products?consumer_key=CONSUMER_KEY
但它的回答是:
{
"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不是日期、id、包括、标题、段塞。所以,我可以按日期,ID,包括,标题和鼻涕虫只订购。我如何按total_sales
订购。有可能做到吗?或者你能建议其他方法吗?
您需要通过函数添加restapi过滤器。php
在主题(或插件文件)中,以确保允许使用meta_键
和meta_值
。
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;
});
您可以添加任何您想添加到枚举值的元键。这样做(而不是添加过滤器来为所有meta_key
添加endpoint)可以防止以元数据形式保存的潜在敏感信息被公开读取。
然后,尝试以下URL:
根据WC v3 API。现在,您可以通过API(据我所知,API是最畅销的产品列表)推出最受欢迎的产品;
GET /wp-json/wc/v3/products?orderby=人气
这应该会让你按销售数量降序获得最受欢迎的产品。这目前没有记录(截至2021年2月2日)。
可能的orderby参数的总列表包括:日期
,id
,包括
,标题
,slug
,修改
,菜单
,价格
,流行度
,评级
我知道这个问题很老,但我写这个函数是因为我和这个问题有相同的问题。
产品的总销售额元数据永远不正确。不要用它。
该函数仅对处理和完成的订单按产品ID求和总销售额,因此不会计算任何取消、退款、未决等。
它基于以下答案:Woocommerce:获取产品的所有订单
function get_total_sales_product_id( $product_id, $order_status = array( 'wc-completed', 'wc-processing' ) ){
global $wpdb;
$order_ids = $wpdb->get_col("
SELECT order_items.order_id
FROM {$wpdb->prefix}woocommerce_order_items as order_items
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
WHERE posts.post_type = 'shop_order'
AND posts.post_status IN ( '" . implode( "','", $order_status ) . "' )
AND order_items.order_item_type = 'line_item'
AND order_item_meta.meta_key = '_product_id'
AND order_item_meta.meta_value = '$product_id'
");
$unique_order_ids = array_unique($order_ids);
$total_sales = 0;
foreach ($unique_order_ids as $order_id) {
$order = wc_get_order($order_id);
foreach ($order->get_items() as $item_key => $item ) {
if ($item->get_product()->get_id() == $product_id) {
$total_sales = $total_sales + $item->get_quantity();
}
}
}
return $total_sales;
}