WooCommerce - 數(shù)量變化時自動更新總價
2023-03-20
php問題
html5模板網(wǎng)
WooCommerce - auto update total price when quantity changed(WooCommerce - 數(shù)量變化時自動更新總價)
本文介紹了WooCommerce - 數(shù)量變化時自動更新總價的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我已經(jīng)找了好幾天了,但還沒有答案.基本上,我試圖用 ajax 調(diào)用替換 woocommerce 標(biāo)準(zhǔn)的更新購物車"按鈕,當(dāng)數(shù)量發(fā)生變化時,它會自動更新訂單總價.這是我的html
<div class="product-thumbnail"><a ><img width="90" height="90" src="縮略圖路徑"/></a>
<div class="product-name"><a class="cart-page-product__title" >Product1 name</a>
<div class="product-quantity"><div class="數(shù)量"><input type="number" step="1" name="cart[some_security_key][qty]" value="1" class="input-text qty text" size="4"/>
<div class="product-subtotal"><span class="amount">2 000</span></div><div class="product-remove"><a class="product-remove_link" >×</a>
<div class="cart_item"><div class="product-thumbnail"><a ><img width="90" height="90" src="縮略圖路徑"/></a>
<div class="product-name"><a class="cart-page-product__title" >Product2 name</a>
<div class="product-quantity"><div class="數(shù)量"><input type="number" step="1" name="cart[some_security_key][qty]" value="1" class="input-text qty text" size="4"/>
<div class="product-subtotal"><span class="amount">2 000</span></div><div class="product-remove"><a class="product-remove_link" >×</a>
在functions.php中,我有一個更新總數(shù)的函數(shù):
公共函數(shù)update_total_price() {check_ajax_referer('update_total_price', 'security');如果(!定義('WOOCOMMERCE_CART')){定義('WOOCOMMERCE_CART',真);}$cart_updated = false;$cart_totals = isset( $_POST['cart'] ) ?$_POST['購物車'] : '';如果(大小(WC()->購物車->get_cart())> 0){foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {$_product = $values['data'];//如果沒有發(fā)布更新的數(shù)量,則跳過產(chǎn)品如果(!isset($_POST['數(shù)量'])){//if ( !isset( $cart_totals[ $cart_item_key ]['qty'] ) ) {繼續(xù);}//消毒$quantity = apply_filters('woocommerce_stock_amount_cart_item', apply_filters('woocommerce_stock_amount', preg_replace("/[^0-9.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)_item), $);//$quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9.]/", '', $cart_totals[ $cart_item_key ]['qty'] ) ), $購物車項鍵 );if ( '' === $quantity || $quantity == $values['quantity'] )繼續(xù);//更新購物車驗證$passed_validation = apply_filters('woocommerce_update_cart_validation', true, $cart_item_key, $values, $quantity );//is_sold_individually如果 ( $_product->is_sold_individually() && $quantity > 1 ) {wc_add_notice( sprintf( __( '您的購物車中只能有 1 %s.', 'woocommerce' ), $_product->get_title() ), 'error' );$passed_validation = false;}如果($passed_validation){WC()->cart->set_quantity( $cart_item_key, $quantity, false );}$cart_updated = true;}}//觸發(fā)操作 - 讓第 3 方在需要時更新購物車并更新 $cart_updated 變量$cart_updated = apply_filters( 'woocommerce_update_cart_action_cart_updated', $cart_updated );如果( $cart_updated ){//重新計算我們的總數(shù)WC()->購物車->calculate_totals();woocommerce_cart_totals();出口;}}
而 Jquery 代碼是:
jQuery( 函數(shù)( $ ) {//wc_cart_params 需要繼續(xù),確保對象存在if ( typeof wc_cart_params === '未定義' ) {返回假;}//購物車價格更新取決于數(shù)量//$( document ).on( 'click', '.quantity', function() {$( document ).on( 'change', '.quantity, input[type=number]', function() {var qty = $( this ).val();var currentVal = parseFloat(數(shù)量);$( 'div.cart_totals' ).block({ message: null, overlayCSS: { background: '#fff url(' + wc_cart_params.ajax_loader_url + ') 無重復(fù)中心', backgroundSize: '16px 16px', opacity: 0.6} });變量數(shù)據(jù) = {動作:'rf_update_total_price',安全性:rf_cart_params.rf_update_total_price_nonce,數(shù)量:currentVal};$.post( rf_cart_params.ajax_url, 數(shù)據(jù), 函數(shù)( 響應(yīng)) {$( 'div.cart_totals' ).replaceWith( response );$('body').trigger('rf_update_total_price');});返回假;});});
如果購物車中只有一種產(chǎn)品,則上述代碼效果很好.
但是當(dāng)我添加一些其他產(chǎn)品并更改其中一個產(chǎn)品的數(shù)量時,我的函數(shù)會使用我所有產(chǎn)品的最后一個數(shù)量值.
例如,第二張圖片的總價必須是 7000(2000*1+2500*2) 但它是 9000(2000*2+2500*2).我是 ajax 和 jquery 的新手,所以感謝您的幫助.
解決方案
這是因為您要更新所有購物車,而不僅僅是產(chǎn)品.
首先,您需要在 javascript 腳本中發(fā)送商品購物車哈希(它不是安全哈希,而是包含所有產(chǎn)品變體的產(chǎn)品哈希):
var item_hash = $( this ).attr( 'name' ).replace(/cart[([w]+)][qty]/g, "$1");變量數(shù)據(jù) = {動作:'rf_update_total_price',安全性:rf_cart_params.rf_update_total_price_nonce,數(shù)量:currentVal,哈希:item_hash};
然后你可以編輯你的函數(shù)update_total_price
,我已經(jīng)簡化了;)
function update_total_price() {//如果 WC_Cart 上沒有發(fā)布更新數(shù)量或沒有哈希值,則跳過產(chǎn)品if( !isset( $_POST['hash'] ) || !isset( $_POST['quantity'] ) ){出口;}$cart_item_key = $_POST['hash'];if(!isset(WC()->cart->get_cart()[$cart_item_key])){出口;}$values = WC()->cart->get_cart()[ $cart_item_key ];$_product = $values['data'];//消毒$quantity = apply_filters('woocommerce_stock_amount_cart_item', apply_filters('woocommerce_stock_amount', preg_replace("/[^0-9.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)_item), $);if ( '' === $quantity || $quantity == $values['quantity'] )出口;//更新購物車驗證$passed_validation = apply_filters('woocommerce_update_cart_validation', true, $cart_item_key, $values, $quantity );//is_sold_individually如果 ( $_product->is_sold_individually() && $quantity > 1 ) {wc_add_notice( sprintf( __( '您的購物車中只能有 1 %s.', 'woocommerce' ), $_product->get_title() ), 'error' );$passed_validation = false;}如果($passed_validation){WC()->cart->set_quantity( $cart_item_key, $quantity, false );}//重新計算我們的總數(shù)WC()->購物車->calculate_totals();woocommerce_cart_totals();出口;}
I've been searching for several days but I have no answer yet. Basically, I'm trying to replace woocommerce standart "update cart" button with ajax call, which automatically updates order total price when quantity changed.
This is my html
<div class="cart_item">
<div class="product-thumbnail">
<a ><img width="90" height="90" src="path to thumbnail"/></a>
</div>
<div class="product-name">
<a class="cart-page-product__title" >Product1 name</a>
</div>
<div class="product-quantity">
<div class="quantity">
<input type="number" step="1" name="cart[some_security_key][qty]" value="1" class="input-text qty text" size="4"/>
</div>
</div>
<div class="product-subtotal"><span class="amount">2 000</span></div>
<div class="product-remove">
<a class="product-remove_link" >×</a>
</div>
</div>
<div class="cart_item">
<div class="product-thumbnail">
<a ><img width="90" height="90" src="path to thumbnail"/></a>
</div>
<div class="product-name">
<a class="cart-page-product__title" >Product2 name</a>
</div>
<div class="product-quantity">
<div class="quantity">
<input type="number" step="1" name="cart[some_security_key][qty]" value="1" class="input-text qty text" size="4"/>
</div>
</div>
<div class="product-subtotal"><span class="amount">2 000</span></div>
<div class="product-remove">
<a class="product-remove_link" >×</a>
</div>
</div>
In functions.php I have a function for updating totals:
public function update_total_price() {
check_ajax_referer( 'update_total_price', 'security' );
if ( ! defined('WOOCOMMERCE_CART') ) {
define( 'WOOCOMMERCE_CART', true );
}
$cart_updated = false;
$cart_totals = isset( $_POST['cart'] ) ? $_POST['cart'] : '';
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
// Skip product if no updated quantity was posted
if ( ! isset( $_POST['quantity'] ) ) {
// if ( ! isset( $cart_totals[ $cart_item_key ]['qty'] ) ) {
continue;
}
// Sanitize
$quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)) ), $cart_item_key );
// $quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9.]/", '', $cart_totals[ $cart_item_key ]['qty'] ) ), $cart_item_key );
if ( '' === $quantity || $quantity == $values['quantity'] )
continue;
// Update cart validation
$passed_validation = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $values, $quantity );
// is_sold_individually
if ( $_product->is_sold_individually() && $quantity > 1 ) {
wc_add_notice( sprintf( __( 'You can only have 1 %s in your cart.', 'woocommerce' ), $_product->get_title() ), 'error' );
$passed_validation = false;
}
if ( $passed_validation ) {
WC()->cart->set_quantity( $cart_item_key, $quantity, false );
}
$cart_updated = true;
}
}
// Trigger action - let 3rd parties update the cart if they need to and update the $cart_updated variable
$cart_updated = apply_filters( 'woocommerce_update_cart_action_cart_updated', $cart_updated );
if ( $cart_updated ) {
// Recalc our totals
WC()->cart->calculate_totals();
woocommerce_cart_totals();
exit;
}
}
And Jquery code is:
jQuery( function( $ ) {
// wc_cart_params is required to continue, ensure the object exists
if ( typeof wc_cart_params === 'undefined' ) {
return false;
}
// Cart price update depends on quantity
//$( document ).on( 'click', '.quantity', function() {
$( document ).on( 'change', '.quantity, input[type=number]', function() {
var qty = $( this ).val();
var currentVal = parseFloat( qty);
$( 'div.cart_totals' ).block({ message: null, overlayCSS: { background: '#fff url(' + wc_cart_params.ajax_loader_url + ') no-repeat center', backgroundSize: '16px 16px', opacity: 0.6 } });
var data = {
action: 'rf_update_total_price',
security: rf_cart_params.rf_update_total_price_nonce,
quantity: currentVal
};
$.post( rf_cart_params.ajax_url, data, function( response ) {
$( 'div.cart_totals' ).replaceWith( response );
$( 'body' ).trigger( 'rf_update_total_price' );
});
return false;
});
});
The above code works great if only one product is in the cart.
But when I add some other product and change quantity of one of them my function use last value of quantity for all of my products.
For example, total price for the second image must be 7000(2000*1+2500*2) but it is 9000(2000*2+2500*2).
I am new to ajax and jquery so appreciate any help.
解決方案
It's because you are updating all your cart, not just a product.
First you need to send the item cart hash (it's not a security hash, but the product hash with all the product variation) on the javascript script:
var item_hash = $( this ).attr( 'name' ).replace(/cart[([w]+)][qty]/g, "$1");
var data = {
action: 'rf_update_total_price',
security: rf_cart_params.rf_update_total_price_nonce,
quantity: currentVal,
hash : item_hash
};
Then you can edit your function update_total_price
, I've simplified ;)
function update_total_price() {
// Skip product if no updated quantity was posted or no hash on WC_Cart
if( !isset( $_POST['hash'] ) || !isset( $_POST['quantity'] ) ){
exit;
}
$cart_item_key = $_POST['hash'];
if( !isset( WC()->cart->get_cart()[ $cart_item_key ] ) ){
exit;
}
$values = WC()->cart->get_cart()[ $cart_item_key ];
$_product = $values['data'];
// Sanitize
$quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)) ), $cart_item_key );
if ( '' === $quantity || $quantity == $values['quantity'] )
exit;
// Update cart validation
$passed_validation = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $values, $quantity );
// is_sold_individually
if ( $_product->is_sold_individually() && $quantity > 1 ) {
wc_add_notice( sprintf( __( 'You can only have 1 %s in your cart.', 'woocommerce' ), $_product->get_title() ), 'error' );
$passed_validation = false;
}
if ( $passed_validation ) {
WC()->cart->set_quantity( $cart_item_key, $quantity, false );
}
// Recalc our totals
WC()->cart->calculate_totals();
woocommerce_cart_totals();
exit;
}
這篇關(guān)于WooCommerce - 數(shù)量變化時自動更新總價的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!
相關(guān)文檔推薦
Cannot use #39;Object as class name as it is reserved Cake 2.2.x(不能使用 Object 作為類名,因為它是保留的 Cake 2.2.x)
Session is lost after an OAuth redirect(OAuth 重定向后會話丟失)
Pagination Sort in Cakephp 3.x(Cakephp 3.x 中的分頁排序)
CakePHP Shared core for multiple apps(CakePHP 多個應(yīng)用程序的共享核心)
Login [ Auth-gt;identify() ] always false on CakePHP 3(在 CakePHP 3 上登錄 [ Auth-identify() ] 始終為 false)
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 87 bytes)(致命錯誤:允許的內(nèi)存大小為 134217728 字節(jié)已用盡(嘗試分配 87 字節(jié)))
主站蜘蛛池模板:
日韩视频一区二区
|
国产精品亚洲成在人线
|
狠狠干av
|
精品久久久久久久久久久下田
|
精品久久久久久久久久久久久久
|
亚洲免费高清
|
波多野结衣一区二区三区
|
精品欧美一区二区三区免费观看
|
国产无套一区二区三区久久
|
欧美激情视频网站
|
久久国产精品无码网站
|
久久精品国产亚洲一区二区三区
|
国产成人精品在线播放
|
成人免费一区二区三区视频网站
|
国产精品久久久久久妇女
|
av一级久久 |
91久久久久久久久久久
|
国产视频福利一区
|
亚洲最色视频
|
国产一区二区三区精品久久久
|
h片在线播放
|
国产精品久久久久久久久久免费
|
日日想夜夜操
|
国产一区二区三区在线免费观看
|
天天天久久久
|
黄色亚洲网站
|
色综合一区二区
|
一区二区三区四区视频
|
日韩欧美精品
|
91精品久久久久久久久中文字幕
|
www.97国产
|
一区二区精品
|
亚洲人的av
|
一区视频
|
午夜在线精品偷拍
|
在线看片网站
|
成人免费三级电影
|
久久一级大片
|
欧美国产精品一区二区三区
|
中文字幕一级毛片视频
|
欧美在线高清
|