我们使用WooCommerce订阅并创建了一个定期优惠券。这意味着在最初的订单上,没有折扣。仅适用于定期订单。默认情况下,WooCommerce会在结账时显示,添加此优惠券后,会显示两倍的优惠券信息。一个位置显示的折扣值为$0,用于总订单,而在一个位置,显示的优惠券代码金额用于经常性订单。
屏幕截图:https://ibb.co/9yKK92X(结账页面(
这看起来很奇怪,因为这是一个优惠券只为经常性订单。因此,它应该只显示在定期订单部分。我试图用下面的代码将优惠券隐藏在总订单部分。但它并没有如预期的那样发挥作用。我也不确定这是否是最好的方法。
有人知道我们该怎么做吗?
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 ); // add filter for all coupons
function filter_woocommerce_coupon_get_discount_amount( $discount, $discounting_amount,
$cart_item, $single, $coupon ) {
// filter the discount if coupon amount is 0
if($discount == 0 && $cart_item['line_subtotal'] == $cart_item['line_total']){
echo "<script>document.querySelector('.cart-discount').style.display = 'none';</script>";
}
return $discount;
}
为什么不直接使用CSS来隐藏它?
您可以简单地将购物车折扣作为目标,不包括定期折扣
例如
.cart-discount:not(.recurring-total) {
diplay: none ;
}
或者使用优惠券中的前1或2个字符作为通配符css选择器来针对特定优惠券并隐藏它。
假设你的优惠券是nananana
,你可以像这样使用前两个字符;
tr[class^="coupon-na"]:not(.recurring-total), tr[class*=" coupon-na"]:not(.recurring-total) {
display: none;
}
如果简单的css不起作用,那么您唯一的选择就是编辑wooccommerce模板文件,即以下
/woocommerce/templates/cart/cart-totals.php
/woocommerce/templates/checkout/review-order.php
查找优惠券上循环的行,类似
<?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
<tr class="cart-discount...">
.
.
.
</tr>
<?php endforeach; ?>
然后添加一个条件,它只在折扣金额大于0
时显示,应该这样做,
<?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
<?php
$totalDiscount = WC()->cart->get_coupon_discount_amount( $coupon->get_code(), WC()->cart->display_cart_ex_tax );
if ( $totalDiscount > 0 ) {
?>
<tr class="cart-discount...">
.
.
.
</tr>
<?php } ?>
<?php endforeach; ?>
编辑
实际上,你可以做一些jquery技巧,尽管它在隐藏优惠券项目方面可能会有延迟,但在下面的例子中,我使用MutationObserver
来监听.shop_table
div内的任何更改,并设置延迟,因为在添加/删除优惠券时,wooccommerce也会修改DOM。因此,在wooccommerce做了一些DOM更改后,代码只运行了50ms
( function($) {
let delay, // set a timer delay
origOrder = $('.shop_table') //get original shop_table div
if ( origOrder.length > 0 ) {
new MutationObserver(() => {
if (delay) clearTimeout(delay) // reset timer delay
delay = setTimeout(() => {
const order = $('.shop_table')
if ( origOrder !== order) { // check for any shop_table div changes
origOrder = order
hideZeroCoupon()
}
}, 50) // run 50ms after DOM modified
}).observe(document, {subtree: true, childList: true})
}
function hideZeroCoupon() {
const orderCoupon = $('.cart-discount').not('.recurring-total')
orderCoupon.each( (key, item) => {
const orderCouponAmount = $(item).find('.amount')
if ( orderCouponAmount.length > 0 ) {
const discount = parseFloat( orderCouponAmount.text().replace(/[^d.-]/g, '') )
if ( discount === 0 ) {
$(item).hide()
}
}
})
}
})(jQuery);