【问题标题】:How to add discount to cart total?如何将折扣添加到购物车总数?
【发布时间】:2015-01-25 18:00:45
【问题描述】:

我需要根据购物车中的产品数量添加折扣,此折扣将适用于购物车的总数。不使用优惠券还有其他选择吗?

【问题讨论】:

标签: wordpress woocommerce


【解决方案1】:

我更喜欢这种方式,我认为更干净

// Hook before calculate fees
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');

/**
 * Add custom fee if more than three article
 * @param WC_Cart $cart
 */
function add_custom_fees( WC_Cart $cart ){
    if( $cart->cart_contents_count < 3 ){
        return;
    }
    
    // Calculate the amount to reduce
    $discount = $cart->subtotal * 0.1;
    $cart->add_fee( 'You have more than 3 items in your cart, a 10% discount has been added.', -$discount);
}

【讨论】:

  • 谢谢,这是一种更好的方法,而不是在使用应用于购物车的动态折扣时使用优惠券代码来混乱后端。
  • 关于每个产品的 WooCommerce 折扣购物车检查此cloudways.com/blog/woocommerce-discount-cart
  • 访客用户购物时,这是否也保存在后端订单中?
【解决方案2】:

这段代码应该可以工作:

add_action('woocommerce_before_cart_table', 'discount_when_produts_in_cart');
function discount_when_produts_in_cart( ) {
    global $woocommerce;
    if( $woocommerce->cart->cart_contents_count > 3 ) {
        $coupon_code = 'maryscode';
        if (!$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code ))) {
            $woocommerce->show_messages();
        }
        echo '<div class="woocommerce_message"><strong>You have more than 3 items in your cart, a 10% discount has been added.</strong></div>';
    }
}

如果客户购物车中有 4 个或更多产品,以上将应用优惠券“maryscode”到购物车。

编辑:将以下内容添加到您的 css 中

.coupon {
    display: none !important;
}

【讨论】:

  • 是的,我已经尝试过这是可行的,但会在购物车页面上显示优惠券字段并应用按钮和消息。
  • @user3714488 转到 Woocommerce 设置 -> 结帐,有一个“优惠券”选项取消选中该框,它不会在购物车页面上显示优惠券字段/应用按钮。
  • 当我取消勾选上面的代码不起作用的选项
  • @user3714488,很抱歉。重新勾选该选项并将我编辑的 CSS 添加到我的帖子中。
猜你喜欢
  • 1970-01-01
  • 2022-12-20
  • 1970-01-01
  • 1970-01-01
  • 2011-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多