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

前端 未结 4 1877
走了就别回头了
走了就别回头了 2021-01-28 06:26

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 stil

4条回答
  •  情书的邮戳
    2021-01-28 07:09

    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.

提交回复
热议问题