Set programmatically product sale price and cart item prices in Woocommerce 3

半腔热情 提交于 2019-12-04 05:35:44

问题


This is the continuation of : Set product sale price programmatically in 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?

Any help is appreciated.


回答1:


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

    }
}

Code goes in function.php file of your active child theme (active theme).

Tested and works.

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



来源:https://stackoverflow.com/questions/48771178/set-programmatically-product-sale-price-and-cart-item-prices-in-woocommerce-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!