[英]Woocommerce Update Price Doesn't Save In Cart Session
我在Wordpress Woocommerce中遇到問題,因此我可以根據他們所需的條件以編程方式更新產品的價格。 以下是一個簡單的示例。 我先顯示它,然后將其添加到購物車中。 我的問題是,當用戶注銷並重新登錄時,購物車最終返回產品的全價。 我可能錯誤地更新了價格,或者有更好的方法來確保購物車具有正確的折扣價。
這是我在functions.php中擁有的東西
add_action('woocommerce_get_price_html','pricechanger');
function pricechanger($price){
$theid = get_the_ID();
$product = wc_get_product($theid);
$price = $product->price;
$price = //do something to the price here
//save the productid/price in session for cart
$_SESSION['pd']['$theid'] = $price;
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10, 2);
add_action( 'init', 'woocommerce_add_to_cart_action', 10);
add_action( 'init', 'woocommerce_checkout_action', 10 );
return $price;
}
因為價格不會過渡到“添加到購物車”按鈕,所以我不得不將它們保存在會話中。 我還沒有找到將價格傳送到購物車的地方。
add_action( 'woocommerce_before_calculate_totals', 'woo_add_discount');
function woo_add_discount() {
if(isset($_SESSION['pd'])) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
foreach($_SESSION['pd'] as $key => $val) {
if($cart_item['data']->id == $key){
$cart_item['data']->set_price($val);
}
}
}
}
}
非常感謝您的幫助! 謝謝!
我忘了在這里發布我的總結性答案。
您需要針對您的價格更改代碼運行以下掛鈎:
add_action( 'woocommerce_before_calculate_totals', 'your_function_here');
add_action( 'woocommerce_before_mini_cart', 'your_function_here');
function your_function_here(){
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
//do something to your price here
$price = 'some calculation here';
//set your price
$cart_item['data']->price = floatval($price);
}
}
希望能對某人有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.