Woocommerce 购物车商品折扣在结账时重置

Woocommerce cart items discount gets reset in checkout

我一直在尝试使用以下代码在我的商店中实施折扣:

add_action('woocommerce_before_calculate_totals', 'set_discount', 10 );

function set_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    // Loop Through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // 50% items discount
        $cart_item['data']->set_price( $cart_item['data']->get_price() / 2 ); 
    }
}

似乎设置价格在结帐时被一些标准 AJAX 重用原始价格或其他请求覆盖。我试过使用 add_fee() 得到相同的结果,我也试过停用所有插件(当然除了 woocommerce),我试过切换到另一个主题 - 没有任何效果!

使用 Wordpress 5.0.3、Woocommerce 3.5.4、Storefront 2.4.2 的子主题


更新:添加了屏幕截图

1) 这是应该在结帐时显示的内容,显示时间约为 1-2 秒:


2) 这是加载微调器完成后显示的内容 - 原价:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

function add_custom_price( $cart_object ) {
    $custom_price = 10; // This will be your custome price  
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $custom_price = ($value['data']->price)/2;
        //$value['data']->price = $custom_price;
        // for WooCommerce version 3+ use: 
         $value['data']->set_price($custom_price);
    }
}

自 Woocommerce 3.2+ 以来避免问题和错误的正确代码是:

add_action('woocommerce_before_calculate_totals', 'cart_item_discount', 10, 1 );
function cart_item_discount( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Avoiding hook repetition (when using price calculations for example)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop Through cart items
    foreach ( $cart->get_cart() as $cart_item ) {

        $original_price   = $cart_item['data']->get_price(); // Get original product price
        $discounted_price = $original_price / 2; // 50 % of discount
        $cart_item['data']->set_price( $discounted_price );
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。测试和工作 (在最新版本上测试:Wordpress 5.0.x | Woocommerce 3.5.x | Storefront 2.4.x)

If it doesn't work, it's because some other things or customizations are interacting with it. You need first to check Woocommerce > Status for red items (where all overridden templates, at the end, need to be up to date).

参见: