Php 显示WooCommerce中类别的总销售额
我试图在每个分类页面的顶部列出产品的总销量 这笔款项的一部分将被捐赠,我的客户想公布这笔款项。我已经找了好几个小时了,试了好几个小时了,没有任何运气。我发现了一个显示整个商店总销售额的插件,但我只想要一个类别 我尝试向这个插件添加另一个过滤器,但没有成功。有什么想法吗Php 显示WooCommerce中类别的总销售额,php,wordpress,woocommerce,filter,Php,Wordpress,Woocommerce,Filter,我试图在每个分类页面的顶部列出产品的总销量 这笔款项的一部分将被捐赠,我的客户想公布这笔款项。我已经找了好几个小时了,试了好几个小时了,没有任何运气。我发现了一个显示整个商店总销售额的插件,但我只想要一个类别 我尝试向这个插件添加另一个过滤器,但没有成功。有什么想法吗 function getSaleAmountbyCategoryID($product_cat_id) { //first getting all the Product ID by Category ID $pr
function getSaleAmountbyCategoryID($product_cat_id)
{
//first getting all the Product ID by Category ID
$pro_args = [
'post_type' => 'product',
'pages_per_post' => -1,
'post_status' => 'publish',
'fields' => 'ids',
'tax_query' => [
[
'taxonomy' => 'product_cat',
'field' => 'term_id', //This is optional, as it defaults to 'term_id'
'terms' => $product_cat_id, //(int)
]
]
];
$product_ids_query = new WP_Query($pro_args);
$include_product_id = $product_ids_query->posts;
//getting all the success orders
$args = [
'post_type' => 'shop_order',
'posts_per_page' => '-1',
'post_status' => ['wc-processing', 'wc-completed', 'wc-onhold']
];
$my_query = new WP_Query($args);
$total = 0;
$orders = $my_query->posts;
foreach ($orders as $ctr => $value)
{
$order_id = $value->ID;
//getting order object
$order = wc_get_order($order_id);
$items = $order->get_items();
foreach ($items as $item_data)
{
$product_id = $item_data['item_meta']['_product_id'][0];
if (in_array($product_id, $include_product_id))
{
//getting product object
//$_product = wc_get_product($product_id);
//$qty = $item_data['item_meta']['_qty'][0];
$pro_price = $item_data['item_meta']['_line_total'][0];
$total += $pro_price;
}
}
}
return $total;
}
将上述代码添加到活动主题functions.php
用法在您的产品类别页面模板中,将其称为
echo getSaleAmountbyCategoryID(21); //replace it by your product caregory ID
请注意:我不会说这是一个最好的解决方案,因为它将是缓慢的,如果你有1000的订单。如果我找到更好的解决方案,我会更新我的答案
希望这有帮助 您需要重新表述和扩展您的问题,并添加您当前的代码。不清楚你在问什么。@bigbluehouse:我很高兴它能帮助你,但请不要忘记接受我的回答,因为它解决了你的问题。我用过它,但没有显示任何东西