如何为购物车总额添加折扣?

时间:2014-11-27 07:49:06

标签: wordpress woocommerce

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

2 个答案:

答案 0 :(得分:22)

我更喜欢这种方式,我认为更清洁

// 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);
}

答案 1 :(得分: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.';
    }
}

以上将适用优惠券&#34; maryscode&#34;如果客户购物车中有4个或更多产品,则推车到购物车。

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

.coupon 
{
    display: none !important;
}