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

如何创建短代码显示优惠券使用次数及对应售出商品数量

创建显示优惠券使用次数及对应售出商品数量的短代码

以下是优化后的代码,既保留优惠券使用次数展示,又新增对应售出商品数量统计,同时符合WordPress和WooCommerce的最佳实践:

function coupon_usage_and_sales_count() {
    $coupon_code = 'coupon-test';
    
    // 获取优惠券对象并验证存在性
    $coupon = new WC_Coupon($coupon_code);
    if (!$coupon->exists()) {
        return '<p>优惠券不存在</p>';
    }
    
    // 获取优惠券已使用次数(使用官方API方法,避免直接访问属性被弃用)
    $usage_count = $coupon->get_usage_count();
    
    // 查询使用过该优惠券的有效订单(仅统计已完成/处理中的订单)
    $order_ids = wc_get_orders(array(
        'status'    => array('completed', 'processing'),
        'coupon'    => $coupon_code,
        'return'    => 'ids',
        'limit'     => -1 // 获取所有符合条件的订单
    ));
    
    $total_sold_items = 0;
    
    // 遍历订单统计商品总数量
    foreach ($order_ids as $order_id) {
        $order = wc_get_order($order_id);
        if ($order) {
            foreach ($order->get_items() as $item) {
                $total_sold_items += $item->get_quantity();
            }
        }
    }
    
    // 格式化输出统计内容
    return sprintf(
        '<div class="coupon-stats">
            <p><strong>优惠券已使用次数:</strong> %d</p>
            <p><strong>对应售出商品总数:</strong> %d</p>
        </div>',
        $usage_count,
        $total_sold_items
    );
}
add_shortcode('coupon_usage_sales_stats', 'coupon_usage_and_sales_count');

关键说明:

  • API规范:使用get_usage_count()而非直接访问$coupon_data->usage_count,适配WooCommerce 3.0+版本要求,避免属性直接访问被弃用的警告。
  • 订单过滤:仅统计completed和processing状态的订单,排除取消、退款等无效订单,确保数据准确。
  • 短代码规范:通过return输出内容而非直接echo,符合WordPress短代码执行逻辑。
  • 错误处理:加入优惠券存在性检查,避免因优惠券不存在导致的页面错误。

使用时,只需在文章或页面中插入短代码 [coupon_usage_sales_stats] 即可显示统计内容。

内容的提问来源于stack exchange,提问作者Dr.Jaber ALShemmari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:45:48