【问题标题】:Display Cart Item subtotal striked when discounted by a coupon in Woocommerce在 Woocommerce 中通过优惠券打折时显示购物车项目小计
【发布时间】:2026-01-31 01:35:01
【问题描述】:

我正在尝试在购物车商品上添加优惠券折扣,我可以这样做,但问题是我不想突出没有优惠券折扣商品的商品。

目前是这样的

但我希望它看起来像这样。

简单来说,我只想突出应用了折扣/优惠券折扣的购物车商品,其他商品价格保持不变。

这是我当前在function.php中的代码

add_filter( 'woocommerce_cart_item_subtotal', 'show_coupon_item_subtotal_discount', 99, 3 );
function show_coupon_item_subtotal_discount( $subtotal, $cart_item, $cart_item_key ){
global $woocommerce;
if ( $woocommerce->cart->has_discount( $coupon_code )) {
$newsubtotal = wc_price( woo_type_of_discount( $cart_item['line_total'], $coupon->discount_type, $coupon->amount ) );
$subtotal = sprintf( '<s>%s</s> %s', $subtotal, $newsubtotal ); 
}
return $subtotal;

}


function woo_type_of_discount( $price, $type, $amount ){
switch( $type ){
case 'percent_product':
$newprice = $price * ( 1 - $amount/100 );
break;
case 'fixed_product':
$newprice = $price - $amount;
break;
case 'percent_cart':
$newprice = $price * ( 1 - $amount/100 );
break;
case 'fixed_cart':
$newprice = $price - $amount;
break;
default:
$newprice = $price;
}

return $newprice;
}

【问题讨论】:

    标签: php wordpress woocommerce cart coupon


    【解决方案1】:

    在购物车中已经有一些有助于优惠券折扣的相关功能,这将简化您尝试做的事情。共有 2 个购物车商品可供选择:

    • 'line_subtotal' 是非打折购物车项目行总计
    • 'line_total' 是打折的购物车商品行总数

    因此不需要外部函数,也不需要检测是否应用了优惠券。所以功能代码将非常紧凑以获得所需的显示:

    add_filter( 'woocommerce_cart_item_subtotal', 'show_coupon_item_subtotal_discount', 100, 3 );
    function show_coupon_item_subtotal_discount( $subtotal, $cart_item, $cart_item_key ){
        if( $cart_item['line_subtotal'] !== $cart_item['line_total'] ) {
            $subtotal = sprintf( '<del>%s</del> <ins>%s</ins>',  wc_price($cart_item['line_subtotal']), wc_price($cart_item['line_total']) );
        }
        return $subtotal;
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。

    【讨论】:

    • LoicTheAztec,你是一个超级开始。非常感谢你帮助我。前几天我被困住了,但你让我开心。
    • 嘿 LoicTheAztec,正如我在您的回答中看到的那样,您肯定更改了单件商品小计的价格,但如果您查看购物车总计,它们仍然是从产品原价计算的。所以你能帮忙吗。因为我也卡住了
    • 那里可能有错字? %s 应该是 %s