使用woocommerce_product_get_price挂钩的结帐价格问题 [英] Checkout price issue using woocommerce_product_get_price hook
问题描述
我需要将Woocommerce前端中每种产品的价格提高一倍。为此,我使用了以下代码:
I need to double the price for every product in Woocommerce frontend. For this I used the following code:
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
return $price*2;
}
但是使用此代码时出错。结帐页面价格不正确。例如,
的产品原始价格为10。我们将此价格乘以此代码。所以现在的产品价格是20当我将该产品添加到购物车中时,购物车和结帐页面的价格为40。这意味着该乘数发生了两次。
But there is an error using this code. checkout page price is not correct. for example the product orginal price is 10. We double the price by this code . so the product price is 20 now. When i added this product to the cart then cart and checkout page price is 40. That means this multiplication is take place in two times.
请帮助解决此问题。
推荐答案
已更新要翻倍价格:
1)首先,您将代码限制为仅单个产品和存档页面:
1) First you will restrict your code to single product and archives pages only:
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
if( is_shop() || is_product_category() || is_product_tag() || is_product() )
return $price*2;
return $price;
}
2)然后,对于购物车和结账页面,您将更改购物车的价格这样:
2) Then for cart and checkout pages, you will change the cart item price this way:
add_filter( 'woocommerce_add_cart_item', 'set_custom_cart_item_prices', 20, 2 );
function set_custom_cart_item_prices( $cart_data, $cart_item_key ) {
// Price calculation
$new_price = $cart_data['data']->get_price() * 2;
// Set and register the new calculated price
$cart_data['data']->set_price( $new_price );
$cart_data['new_price'] = $new_price;
return $cart_data;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'set_custom_cart_item_prices_from_session', 20, 3 );
function set_custom_cart_item_prices_from_session( $session_data, $values, $key ) {
if ( ! isset( $session_data['new_price'] ) || empty ( $session_data['new_price'] ) )
return $session_data;
// Get the new calculated price and update cart session item price
$session_data['data']->set_price( $session_data['new_price'] );
return $session_data;
}
代码包含在您活动的子主题的function.php文件中(
经过测试并可以正常工作。它将改变您在购物车,结帐和订购页面中所期望的所有价格……
Tested and working. It will change all prices as you expect in cart, checkout and order pages…
这篇关于使用woocommerce_product_get_price挂钩的结帐价格问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!