显示WooCommerce中类别的总销售额

问题描述:

我试图列出每个类别页面顶部销售的产品总数显示WooCommerce中类别的总销售额

这个总数的药水将被捐赠,我的客户想要宣传这个数额。我一直在寻找和尝试几个小时,并没有运气。我发现了一个显示整个商店总销售额的插件,但我只想要一个类别。

我试着给这个插件添加另一个过滤器,但没有运气。有什么想法吗?

+0

您需要改写和扩展您的问题,并添加您当前的代码。你问的问题很不清楚。 –

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个订单,它会很慢。如果我找到更好的解决方案,我会更新我的答案。

希望这会有所帮助!

+0

谢谢!这就像一个魅力! – bigbluehouse

+0

@bigbluehouse:我很高兴它可以帮助你,但请不要忘记接受我的答案,因为它可以解决你的问题。 –