我正在寻找一个代码片段,以获取今天每种产品的总销售额,因此可以在我的theme functions.php文件中使用它。
输出应如下所示(每件商品的销售总额):
Product xxx = 25 orders
Product yyy = 18 orders
Product zzz = 8 orders
答案 0 :(得分:2)
这可以通过以下非常简单的SQL查询和foreach循环来完成。
这将为您提供过去24小时内按产品计数的订单产品(以及产品变体,但没有父变量产品)的列表:
global $wpdb;
$results = $wpdb->get_results( "
SELECT DISTINCT woim.meta_value as id, COUNT(woi.order_id) as count, woi.order_item_name as name
FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim
INNER JOIN {$wpdb->prefix}woocommerce_order_items as woi ON woi.order_item_id = woim.order_item_id
INNER JOIN {$wpdb->prefix}posts as p ON p.ID = woi.order_id
WHERE p.post_status IN ('wc-processing','wc-on-hold')
AND UNIX_TIMESTAMP(p.post_date) >= (UNIX_TIMESTAMP(NOW()) - (86400))
AND ((woim.meta_key LIKE '_variation_id' AND woim.meta_value > 0)
OR (woim.meta_key LIKE '_product_id'
AND woim.meta_value NOT IN (SELECT DISTINCT post_parent FROM {$wpdb->prefix}posts WHERE post_type LIKE 'product_variation')))
GROUP BY woim.meta_value
" );
// Loop though each product
foreach( $results as $result ){
$product_id = $result->id;
$product_name = $result->name;
$orders_count = $result->count;
// Formatted Output
echo 'Product: ' . $product_name .' (' . $product_id . ') = ' . $orders_count . '<br>';
}
经过测试可以正常工作。
如果您要改为基于“今天”日期获取总数,则将以下行替换为代码:
AND UNIX_TIMESTAMP(p.post_date) >= (UNIX_TIMESTAMP(NOW()) - (86400))
通过此行:
AND DATE(p.post_date) >= CURDATE()
时区调整,使用
CONVERT_TZ()
SQL function
(您将在何处进行调整'+10:00'
最后一个参数作为与时区匹配的偏移量)AND DATE(p.post_date) >= DATE(CONVERT_TZ( NOW(),'+00:00','+10:00'))
相关的类似答案: