Php WooCommerce-数量更改时自动更新总价

Php WooCommerce-数量更改时自动更新总价,php,jquery,wordpress,woocommerce,Php,Jquery,Wordpress,Woocommerce,我已经找了好几天了,但还没有答案。基本上,我试图用ajax调用替换woocommerce标准的“更新购物车”按钮,当数量发生变化时,它会自动更新订单总价。 这是我的html <div class="cart_item"> <div class="product-thumbnail"> <a href="http://example.com"><img width="90" height="90" src="path to thum

我已经找了好几天了,但还没有答案。基本上,我试图用ajax调用替换woocommerce标准的“更新购物车”按钮,当数量发生变化时,它会自动更新订单总价。 这是我的html

<div class="cart_item">
    <div class="product-thumbnail">
        <a href="http://example.com"><img width="90" height="90" src="path to thumbnail"/></a>
    </div>

    <div class="product-name">
        <a class="cart-page-product__title" href="http://example.com">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" href="http://example.com/?remove_item">&times;</a>
        </div>
</div>
<div class="cart_item">
    <div class="product-thumbnail">
        <a href="http://example.com"><img width="90" height="90" src="path to thumbnail"/></a>
    </div>

    <div class="product-name">
        <a class="cart-page-product__title" href="http://example.com">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" href="http://example.com/?remove_item">&times;</a>
        </div>
</div>
Jquery代码是:

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;
    });
});
如果购物车中只有一种产品,上述代码非常有效。

但是,当我添加一些其他产品并更改其中一个产品的数量时,我的函数将使用所有产品数量的最后一个值

例如,第二个图像的总价必须是7000(2000*1+2500*2),但它是9000(2000*2+2500*2)。
我不熟悉ajax和jquery,因此非常感谢您的帮助。

这是因为您正在更新所有购物车,而不仅仅是一个产品

首先,您需要在javascript脚本上发送商品购物车散列(它不是安全散列,而是包含所有产品变体的产品散列):

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 
    };
然后,您可以编辑您的
功能更新\u总价
,我简化了;)


这里有一个更简单的实现方法。所有的功劳都归于他

//我们将把它挂在优先级31上,这样它就会显示在“添加到购物车”按钮下面。
添加行动(“woocommerce\u单一产品汇总”、“woocommerce\u产品总价”,31);
功能商业\产品总额\价格(){
全球$商业$产品;
//让我们来设置我们的div
echo sprintf(“%s%s”、“产品总数”、“woocommerce”)、“..Product->get_price()”);
echo sprintf(“%s%s”、“购物车总数”、“woocommerce”)、“..product->get_price()”);
?>
jQuery(函数($){
var价格=,
当前购物车总数=,
货币='';
$('[name=quantity]')。更改(函数(){
如果(!(this.value<1)){
var product_total=parseFloat(价格*此值),
购物车总数=浮动(产品购物车总数+当前购物车总数);
$('product#u total_price.price').html(货币+product_total.toFixed(2));
$('cart#u total_price.price').html(货币+cart_total.toFixed(2));
}

$(“#产品#总价,#购物车#总价”).toggle(!(this.value自WooCommerce 2.6.0于2016年6月发布以来,WooCommerce购物车页面在点击更新购物车按钮后使用Ajax更新购物车总价。WooCommerce 2.6.0需要WP 4.4或更新版本

无需担心后端和创建自己的Ajax调用,可以使用分配给Update cart按钮的调用

要实现这一功能,您可以使用我的免费插件,它还有一些方便的附加选项:

或者使用子主题执行以下操作。隐藏更新购物车按钮,然后将触发购物车页面数量更改上默认更新购物车事件的脚本排入队列(适用于购物车和迷你购物车小部件)。使用模板重定向挂钩、依赖项和jQuery,并确保此脚本仅在购物车页面上加载

要使用CSS隐藏按钮,请使用class.button而不是tag,以使其与所有WooCommerce版本兼容:

.button[name='update_cart'] {
    display: none!important;
}
或使用PHP头部样式隐藏按钮:

add_action('wp_head', 'hide_update_cart_button', 20);
function hide_update_cart_button() {
    echo "<style>.button[name='update_cart']{ display: none!important;}</style>";
}
jQuery代码最重要也是通常被忽略的一点是设置更新延迟,1000在本例中,我的插件允许在设置中更改此值。如果用户在此延迟期间再次更改数量,它将重置为完整持续时间。如果未实现此功能,并且您通过单击“增量”按钮将数量从1更改为10,它将我将触发9个Ajax调用,而不是1个。请将其放入.js文件:

var timeout;

jQuery('div.woocommerce').on('change keyup mouseup', 'input.qty', function(){ // keyup and mouseup for Firefox support
    if (timeout != undefined) clearTimeout(timeout); //cancel previously scheduled event
    if (jQuery(this).val() == '') return; //qty empty, instead of removing item from cart, do nothing
    timeout = setTimeout(function() {
        jQuery('[name="update_cart"]').trigger('click');
    }, 1000 );
});

这里缺少的是,
rf\u cart\u参数
是如何设置的?如果调用上面的jQuery函数,我会得到一个
ReferenceError:rf\u cart\u参数没有定义
。可能原因是,我甚至没有加载购物车页面,我在产品归档页面上显示购物车(事实上,我检查了它,当我在原始购物车页面上尝试代码时,它是相同的问题….)。那么如何加载脚本/设置变量呢?。实际上,我现在在购物车页面上找到了该对象,但其名为
wc\u cart\u params
。将尝试在我的存档页面上对这些对象进行加密。这个答案与问题没有任何关系。虽然它可能正确计算价格,但此工具仅用于计算pr上的价格odcut页面,而问题是关于购物车页面。当你在购物车页面上更改数量而不将其提交给wc时,价格可能会改变,但购物车不会改变。@honk31你是对的!没有注意到。我想它仍然值得保留在这里,因为它可能会在将来帮助别人
.button[name='update_cart'] {
    display: none!important;
}
add_action('wp_head', 'hide_update_cart_button', 20);
function hide_update_cart_button() {
    echo "<style>.button[name='update_cart']{ display: none!important;}</style>";
}
add_action( 'template_redirect', 'auto_update_cart_totals' );
function auto_update_cart_totals() {    
    if (! is_cart() ) return; // Only if it's cart page.
    // Enqueue js file.
    add_action( 'wp_enqueue_scripts', 'my_cart_autoupdate' );           
}

function my_cart_autoupdate( ) {
    // Here goes code to hide CSS button if you decide to use PHP solution for styling.

    wp_enqueue_script( 'my-cart-autoupdate', 'path-to-js-file-its-name-and-extension', array('jquery'), '', true);
}
var timeout;

jQuery('div.woocommerce').on('change keyup mouseup', 'input.qty', function(){ // keyup and mouseup for Firefox support
    if (timeout != undefined) clearTimeout(timeout); //cancel previously scheduled event
    if (jQuery(this).val() == '') return; //qty empty, instead of removing item from cart, do nothing
    timeout = setTimeout(function() {
        jQuery('[name="update_cart"]').trigger('click');
    }, 1000 );
});