2017-02-23 135 views
0

我試圖列出每個類別頁面頂部銷售的產品總數顯示WooCommerce中類別的總銷售額

這個總數的藥水將被捐贈,我的客戶想要宣傳這個數額。我一直在尋找和嘗試幾個小時,並沒有運氣。我發現了一個顯示整個商店總銷售額的插件,但我只想要一個類別。

我試着給這個插件添加另一個過濾器,但沒有運氣。有什麼想法嗎?

+0

您需要改寫和擴展您的問題,並添加您當前的代碼。你問的問題很不清楚。 –

回答

1
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:我很高興它可以幫助你,但請不要忘記接受我的答案,因爲它可以解決你的問題。 –