【问题标题】:WooCommerce set cart quantity with AJAX?WooCommerce 使用 AJAX 设置购物车数量?
【发布时间】:2021-11-11 13:28:10
【问题描述】:

这几天我一直在摸不着头脑,需要一些指点。

我正在为 WooCommerce 网站完全从头开始制作自定义主题,现在我正在尝试让购物车功能正常工作。我一直在尝试使用按钮 (+/-) 来更新购物车中产品的数量。

对我来说,问题似乎是我在functions.php 中使用的WC() 与当前的前端会话不是同一个实例,或者这些行中的某个实例。至少我现在的想法。

如果我调试正确,WC()->cart->set_quantity($cart_item_key, 0) 没有错误(如果使用数字 0),所有其他数字都会给出“500(内部服务器错误)”。但即使购物车中的数量为 0,也永远不会改变。

我已正确地将脚本排入队列,因此单击按钮时 AJAX 函数调用可以正常执行。

这是我的 HTML 和 PHP(简化版

<div class="cart-items">
    <?php foreach(WC()->cart->get_cart() as $cart_item_key => $cart_item) : ?>
    <div class="cart-item">
        <div class="quantity" id="cart-qty-<?php echo $cart_item_key ?>">
            <button class="minus" id="cart-subtract"
                onclick="updateCartQuantity('<?php echo $cart_item_key ?>', '<?php echo $cart_item['quantity'] ?>', -1)">-</button>
            <p><?php echo $cart_item['quantity'] ?></p>
            <button class="plus" id="cart-add">+</button>
        </div>
    </div>
    <? endforeach; ?>
</div>

这是我的 JS(在一个名为 shopping-ajax.js 的文件中)

function updateCartQuantity(cart_item_key, current_qty, value) {
  function qty_cart() {
    jQuery.ajax({
      type: "POST",
      url: my_ajax_object.ajax_url,
      data: {
        action: "update_cart",
        hash: cart_item_key,
        quantity: current_qty,
        value: value,
      },
      success: function (data) {
        console.log(data);
      },
      error: function (data) {
        console.log(data);
      },
    });
  }

  qty_cart();
}

这是我的 PHP 函数(functions.php 内)

function updateCartQuantity(){
    $cart_item_key = $_REQUEST['cart_item_key'];
    $quantity = $_REQUEST['quantity'];
    $value = $_REQUEST['value'];
    
    WC()->cart->set_quantity($cart_item_key, $quantity + $value);

    echo $quantity + $value;
    wp_die();
}
add_action( 'wp_ajax_nopriv_update_cart', 'updateCartQuantity' );
add_action( 'wp_ajax_update_cart', 'updateCartQuantity' );

非常感谢您提前提供的任何帮助或指导!

【问题讨论】:

    标签: javascript php ajax wordpress woocommerce


    【解决方案1】:

    您应该根据数量输入框管理产品数量(更改数量)。

    我的 JS:

    位置:主题目录 -> js -> custom.js

    jQuery( function( $ ) {
        $( document ).on( 'change', 'input.qty', function() {
            var $thisbutton = $(this);
            var item_hash = $( this ).attr( 'name' ).replace(/cart\[([\w]+)\]\[qty\]/g, "$1");
            var item_quantity = $( this ).val();
            var currentVal = parseFloat(item_quantity);
            $.ajax({
                type: 'POST',
                url: cart_qty_ajax.ajax_url,
                data: {
                    action: 'my_cart_qty',
                    hash: item_hash,
                    quantity: currentVal
                },
                success: function(response) {
                    jQuery(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]);
                    //jQuery(document.body).trigger('update_checkout');
                }
            });  
        });
    });
    

    functions.php -

    设置排队 Ajax 脚本:

    function enqueue_cart_qty_ajax() {
    
        wp_register_script( 'my_cart_qty-ajax-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '', true );
        wp_localize_script( 'my_cart_qty-ajax-js', 'cart_qty_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
        wp_enqueue_script( 'my_cart_qty-ajax-js' );
    
    }
    add_action('wp_enqueue_scripts', 'enqueue_cart_qty_ajax');
    

    Ajax 调用 -

    function ajax_my_cart_qty() {
    
        // Set item key as the hash found in input.qty's name
        $cart_item_key = $_POST['hash'];
    
        // Get the array of values owned by the product we're updating
        $threeball_product_values = WC()->cart->get_cart_item( $cart_item_key );
    
        // Get the quantity of the item in the cart
        $threeball_product_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 );
    
        // Update cart validation
        $passed_validation  = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $threeball_product_values, $threeball_product_quantity );
    
        // Update the quantity of the item in the cart
        if ( $passed_validation ) {
            WC()->cart->set_quantity( $cart_item_key, $threeball_product_quantity, true );
        }
    
        // Refresh the page
        echo do_shortcode( '[woocommerce_cart]' );
    
        die();
    
    }
    
    add_action('wp_ajax_my_cart_qty', 'ajax_my_cart_qty');
    add_action('wp_ajax_nopriv_my_cart_qty', 'ajax_my_cart_qty');
    

    【讨论】:

    • 感谢您的回答,但您的代码仍然无法正常工作。我仍然收到“500(内部服务器错误)”,这是导致它的原因:WC()-&gt;cart-&gt;set_quantity( $cart_item_key, $threeball_product_quantity, true );
    • 正确地检查 URL“cart_qty_ajax.ajax_url”,因为当我在我的 WordPress 网站上检查此代码时,它的工作率为 100%。我在我的 WordPress 网站上测试后分享了这段代码。
    • 检查并正确,AJAX调用执行。挖掘后似乎出现了无法正确获取推车的问题,WC()-&gt;cart-&gt;get_cart_item( $cart_item_key )WC()-&gt;cart-&gt;set_quantity( $cart_item_key, $threeball_product_quantity, true ); 都不起作用。我确实得到了正确的$cart_item_key,所以我不明白为什么会这样。对我来说,WC() 似乎是问题所在,但我不知道为什么...function ajax_my_cart_qty() 在 functions.php 文件中
    • 如果 wc 有问题,请不要担心,您可以添加 global $woocommerce;在函数函数 ajax_my_cart_qty() 的顶部,像这样-函数 ajax_my_cart_qty() { global $woocommerce;并将 WC()->cart-> 替换为 $woocommerce->cart-> 每个地方都像这样: $woocommerce->cart->get_cart_item($cart_item_key);
    • 这很奇怪,我试过gloabl $woocommerce,但结果相同......嗯。
    猜你喜欢
    • 2016-10-09
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 2018-09-16
    • 2015-11-21
    • 2013-07-22
    • 1970-01-01
    相关资源
    最近更新 更多