WooCommerce仪表盘报表中有一个按分类统计销售额的功能,可以非常方便的查看哪个分类中的产品最受欢迎。我们可以把这个功能显示在前端,实现一个类似「热门分类」的功能,WooCommerce 没有为我们提供直接按分类获取产品销售额的功能,我们需要自行实现一下。

实现按分类统计总销售额的功能

按分类获取订单

首先,我们需要按分类获取订单,我们需要先获取指定分类里面的文章,然后再查询数据库获取订单项目中包含这些产品的订单。

function wprs_get_orders_by_product_cat($cat_slug, $order_status = ['wc-completed'])
{
    global $wpdb;

    $args        = [
        'limit'    => -1,
        'status'   => 'publish',
        'return'   => 'ids',
        'category' => [$cat_slug],
    ];

    $product_ids = wc_get_products($args);

    $results     = $wpdb->get_col("
        SELECT order_items.order_id
        FROM {$wpdb->prefix}woocommerce_order_items as order_items
        LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
        LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
        WHERE posts.post_type = 'shop_order'
        AND posts.post_status IN ( '" . implode("','", $order_status) . "' )
        AND order_items.order_item_type = 'line_item'
        AND order_item_meta.meta_key = '_product_id'
        AND order_item_meta.meta_value IN ( '" . implode("','", $product_ids) . "' )
    ");

    return $results;
}

计算总销售额

有了上面按分类获取订单的功能,我们只需要计算这些订单的总销售额就可以了。

function wprs_cat_sales($cat_slug)
{
    $orders = wprs_get_orders_by_product_cat($cat_slug);
    $total  = 0;
    foreach ($orders as $order_id) {
        foreach (wc_get_order($order_id)->get_items() as $key => $item) {
            $product_id = $item->get_product_id();
            if ( ! $product_id) {
                continue;
            }
            if (has_term($cat_slug, 'product_cat', $product_id)) {
                $total += $item->get_total();
            }
        }
    }

    return wc_price($total);
}

最后,在需要的地方调用 wprs_cat_sales 这个函数即可显示指定分类中的产品总销售额了,对于一些想要在站点优先推广的分类,可以让用户很清楚的了解到哪个分类最热销,容易引起顾客的购买欲望。