本文介绍了仅对Woocommerce中的第二个购物车项目应用折扣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取和修改购物车中的第二项价格?

How to get and modify price of the second item in my cart?

我想在第二个产品上打折-3%(购物车中的物品已经按价格排序,最高价).

I want to made discount -3% on the second product (items in cart already sorted by the price, highest top).

我认为它必须以woocommerce_before_calculate_totals计算或像woocommerce_cart_calculate_fees中的折扣一样?

I think it must calculate in woocommerce_before_calculate_totals or like discount in woocommerce_cart_calculate_fees?

谢谢

推荐答案

更新 (添加了与Woocommerce 3+的兼容性)

对于产品项,最好使用 woocommerce_before_calculate_totals 操作挂钩:

For a product item is better to use woocommerce_before_calculate_totals action hook:

add_action( 'woocommerce_before_calculate_totals', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart ) {

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

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Initialising
    $count = 0;
    $percentage = 3; // 3 %

    // Iterating though each cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        $count++;
        if( 2 == $count){ // Second item only
            $price = $cart_item['data']->get_price(); // product price
            $discounted_price = $price * (1 - ($percentage / 100)); // calculation

            // Set the new price
            $cart_item['data']->set_price( $discounted_price );
            break; // stop the loop
        }
    }
}

或使用购物车折扣(购物车负费用):

Or using a cart discount (negative cart fee):

add_action( 'woocommerce_cart_calculate_fees', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart ) {

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

    // Initialising
    $count = 0;
    $percentage = 3; // 3 %

    // Iterating though each cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        $count++;
        if( 2 == $count){ // Second item only
            $price = $cart_item['data']->get_price(); // product price
            $discount = $price * $percentage / 100; // calculation
            $second_item = true;
            break; // stop the loop
        }
    }
    if( isset($discount) && $discount > 0 )
        $cart->add_fee( __("2nd item 3% discount", 'woocommerce'), -$discount );
}

代码会出现在您活动的子主题(或主题)的function.php文件中,也可能会出现在任何插件文件中.

此代码已经过测试并且可以正常工作.

This code is tested and works.

这篇关于仅对Woocommerce中的第二个购物车项目应用折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:51