在 Woocommerce 3 中以编程方式设置产品销售价格和购物车项目价格

2021-12-22 00:00:00 php wordpress woocommerce cart price

这是继续:在 WooCommerce 中以编程方式设置产品销售价格3

答案有效,但是一旦用户将产品添加到购物车,结帐时仍会显示旧价格.

The answer works, however once a user adds the product to cart, the old price still shows up on checkout.

如何在购物车和结帐页面上获取购物车商品的正确销售价格?

How to get the correct sale price on cart and checkout pages for cart items?

感谢任何帮助.

推荐答案

让它适用于购物车和结帐页面(以及订单和电子邮件通知)的缺失部分是一个非常简单的技巧:

The missing part to get it work for for cart and checkout pages (and also Orders and email notifications too) is a very simple trick:

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

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

    // Iterate through each cart item
    foreach( $cart->get_cart() as $cart_item ) {
        $price = $cart_item['data']->get_sale_price(); // get sale price
        $cart_item['data']->set_price( $price ); // Set the sale price

    }
}

代码位于您的活动子主题(活动主题)的 function.php 文件中.

经过测试并有效.

所以代码只是将产品销售价格设置为购物车项目中的产品价格,并且它可以工作.

So the code just set the product sale price as the product price in cart items and it works.

相关文章