在Woocommerce中降低成本的产品的购物车折扣

时间:2018-04-06 13:08:15

标签: php wordpress woocommerce cart discount

如何在产品购物车中为成本较低的产品应用折扣?

例如:
我有两个购物车产品:一个150美元和一个200美元。我想仅对价格较低的产品申请10%的折扣,在这种情况下是第一个。

我有这个代码,但它仅适用于购物车中的第二个产品:

add_filter( 'woocommerce_before_calculate_totals', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Initialising
    $count = 0;
    $discount = 0.10; // 10 %
    $discounted = 0;
    // Iterating though each cart items
    foreach ( $cart_object->get_cart() as $cart_item ) {
        $count++;
        if( 2 == $count){ // Second item only
            $price = $cart_item['data']->get_price(); // product price
            $discounted_price = $price - ($price * $discount); // calculation
            $discounted = $price - $discounted_price;
            // Set the new price
            //$cart_item['data']->set_price( $discounted_price );
            break; // stop the loop
        }
    }

    $cart_object->add_fee( "Discount (10%) on second product", -$discounted, true );
}

1 个答案:

答案 0 :(得分:0)

对于购物车费用,您应该使用woocommerce_cart_calculate_fees专用挂钩代替:

add_action('woocommerce_cart_calculate_fees', 'discount_on_cheapest_cart_item', 20, 1 );
function discount_on_cheapest_cart_item( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
        return;

    // Only for 2 items or more
    if ( $cart->get_cart_contents_count() < 2 ) return;

    // Initialising
    $percentage = 10; // 10 %
    $discount = 0;
    $item_prices = array();

    // Loop though each cart items and set prices in an array
    foreach ( $cart->get_cart() as $cart_item ) {
        $product_prices_excl_tax[] = wc_get_price_excluding_tax( $cart_item['data'] );
    }
    sort($product_prices_excl_tax);

    $discount = reset($product_prices_excl_tax) * $percentage / 100;

    $cart->add_fee( "Discount on cheapest (".$percentage."%)", -$discount );
}

代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作。