显示WooCommerce中类别的总销售额

时间:2017-02-23 03:34:33

标签: php wordpress filter woocommerce sales

我正在尝试列出每个类别页面顶部的销售产品总量

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

我尝试在此插件中添加另一个过滤器,但没有运气。有什么想法吗?

1 个答案:

答案 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

<强> USAGE
在您的产品类别页面模板中,将其命名为

echo getSaleAmountbyCategoryID(21); //replace it by your product caregory ID

请注意:我不会说这是一个最好的解决方案,因为如果您有1000个订单会很慢。如果我找到更好的解决方案,我会更新我的答案。

希望这有帮助!