You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取WooCommerce特定商品的退货数量以计算退货占比?

统计WooCommerce特定商品的退货占比

自定义函数获取商品总退货数量

WooCommerce没有直接获取商品退货量的函数,但可以通过查询退款订单中的商品明细高效统计,无需手动筛选所有订单。以下是封装好的函数,传入产品ID即可返回总退货数量:

function get_product_total_refunds( $product_id ) {
    $total_refunds = 0;

    // 查询所有已退款的订单
    $refund_orders = wc_get_orders( array(
        'status' => 'refunded',
        'limit'  => -1, // 获取所有退款订单
        'return' => 'ids', // 只返回订单ID,提升效率
    ) );

    foreach ( $refund_orders as $order_id ) {
        $order = wc_get_order( $order_id );
        
        // 遍历订单中的退款条目
        foreach ( $order->get_refunds() as $refund ) {
            foreach ( $refund->get_items() as $item ) {
                // 匹配目标产品ID,累加退货数量
                if ( $item->get_product_id() == $product_id ) {
                    $total_refunds += $item->get_quantity();
                }
            }
        }
    }

    return $total_refunds;
}

计算退货占比

结合你已有的get_total_sales()方法,直接调用函数计算占比:

$product_id = 93;
$product = wc_get_product( $product_id );

$total_sales = $product->get_total_sales();
$total_refunds = get_product_total_refunds( $product_id );

// 避免除以0的情况
if ( $total_sales > 0 ) {
    $refund_rate = ( $total_refunds / $total_sales ) * 100;
    // 保留两位小数输出
    echo '退货占比:' . number_format( $refund_rate, 2 ) . '%';
} else {
    echo '该商品暂无销量';
}

优化说明

  • 使用wc_get_orders只返回订单ID,减少内存占用,比直接返回完整订单对象更高效
  • 遍历退款条目而非整个订单,精准统计目标商品的退货数量
  • 处理了销量为0的边界情况,避免计算错误

内容的提问来源于stack exchange,提问作者mikolaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 15:44:55