woocommerce_before_calculate_totals fires twice

Posted in :

我使用了 dynamic-price-and-discounts-for-woocommerce plugin ,計算的價格會出錯,原因是因為 calculate_totals 會被執行多次。

 

在 class-wc-cart.php 裡可以看到:

public function __construct() {
	$this->session          = new WC_Cart_Session( $this );
	$this->fees_api         = new WC_Cart_Fees( $this );
	$this->tax_display_cart = get_option( 'woocommerce_tax_display_cart' );

	// Register hooks for the objects.
	$this->session->init();

	add_action( 'woocommerce_add_to_cart', array( $this, 'calculate_totals' ), 20, 0 );
	add_action( 'woocommerce_applied_coupon', array( $this, 'calculate_totals' ), 20, 0 );
	add_action( 'woocommerce_cart_item_removed', array( $this, 'calculate_totals' ), 20, 0 );
	add_action( 'woocommerce_cart_item_restored', array( $this, 'calculate_totals' ), 20, 0 );
	add_action( 'woocommerce_check_cart_items', array( $this, 'check_cart_items' ), 1 );
	add_action( 'woocommerce_check_cart_items', array( $this, 'check_cart_coupons' ), 1 );
	add_action( 'woocommerce_after_checkout_validation', array( $this, 'check_customer_coupons' ), 1 );
}

由於 calculate_totals 執行多次,所以 woocommerce_before_calculate_totals 也會被執行多次,所以放在 $cart_object 裡的變數也會被寫入多次,解法是在woocommerce_before_calculate_totals 裡,請勿取出$cart_object 的 price, 而是再從 product object 裡去取出 price 即可。

I see exactly the same issue – my hooked function is firing twice, leading to the option price being added at 2x the cost. My solution was to load the product, get the price from that and then add my incremental cost to that.

function tbk_woo_update_option_price( $cart_object ) {

$option_price = 3.50;
foreach ( $cart_object->get_cart() as $cart_item_key => $cart_item ) {

        $item_id = $cart_item['data']->id;
        //Hook seems to be firing twice for some reason... Get the price from the original product data, not from the cart...
        $product = wc_get_product( $item_id );
        $original_price = $product->get_price();
        $new_price = $original_price + $option_price;
        $cart_item['data']->set_price( $new_price );
}

} add_action( ‘woocommerce_before_calculate_totals’, ‘tbk_woo_update_option_price’, 1000, 1 );

 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *