首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在woocommerce中增加/减少产品数量时从商店页面更新购物车?

在 WooCommerce 中,可以通过使用 Ajax 技术来实现在商店页面上增加/减少产品数量时实时更新购物车。以下是实现该功能的步骤:

  1. 首先,需要在 WooCommerce 主题的 functions.php 文件中添加以下代码来启用 Ajax 功能:
代码语言:txt
复制
add_action('wp_enqueue_scripts', 'custom_ajax_scripts');
function custom_ajax_scripts() {
    wp_enqueue_script('custom-ajax-script', get_stylesheet_directory_uri() . '/js/custom-ajax.js', array('jquery'), '1.0', true);
    wp_localize_script('custom-ajax-script', 'custom_ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
  1. 在 WooCommerce 主题的 js 文件夹中创建一个名为 custom-ajax.js 的文件,并添加以下代码:
代码语言:txt
复制
jQuery(document).ready(function($) {
    $('.quantity').on('click', '.plus, .minus', function() {
        var $quantityInput = $(this).closest('.quantity').find('input.qty');
        var currentVal = parseFloat($quantityInput.val());
        var maxVal = parseFloat($quantityInput.attr('max'));
        var minVal = parseFloat($quantityInput.attr('min'));
        var step = parseFloat($quantityInput.attr('step'));

        if ($(this).is('.plus')) {
            if (maxVal && (currentVal >= maxVal)) {
                $quantityInput.val(maxVal);
            } else {
                $quantityInput.val(currentVal + step);
            }
        } else {
            if (minVal && (currentVal <= minVal)) {
                $quantityInput.val(minVal);
            } else if (currentVal > 0) {
                $quantityInput.val(currentVal - step);
            }
        }

        $quantityInput.trigger('change');
        return false;
    });
});
  1. 接下来,需要在 WooCommerce 主题的 functions.php 文件中添加以下代码来处理 Ajax 请求:
代码语言:txt
复制
add_action('wp_ajax_update_cart', 'custom_update_cart');
add_action('wp_ajax_nopriv_update_cart', 'custom_update_cart');
function custom_update_cart() {
    if (isset($_POST['product_id'], $_POST['quantity'])) {
        $product_id = absint($_POST['product_id']);
        $quantity = wc_stock_amount($_POST['quantity']);
        WC()->cart->set_quantity($product_id, $quantity, true);
        WC()->cart->calculate_totals();
        WC_AJAX::get_refreshed_fragments();
    }
    die();
}
  1. 最后,在 WooCommerce 主题的购物车页面模板文件中,找到显示产品数量的输入框,并确保其具有以下属性:
代码语言:txt
复制
<input type="number" class="input-text qty text" step="1" min="0" max="" name="quantity" value="1" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric">

现在,当用户在商店页面上增加/减少产品数量时,购物车将实时更新,而无需刷新整个页面。

请注意,以上代码仅为示例,实际应用中可能需要根据具体情况进行调整。此外,腾讯云并没有与 WooCommerce 直接相关的产品或服务,因此无法提供相关产品和链接。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券