【问题标题】:Remove item from Woocommerce minicart using ajax使用 ajax 从 Woocommerce 迷你购物车中删除项目
【发布时间】:2021-04-02 00:05:17
【问题描述】:

我正在使用 Woocommerce,我正在尝试使用 ajax 从迷你购物车中删除商品。

通过查看 woocommerce minicart.php 文件,我发现了删除项目的相关功能:

<?php
echo apply_filters( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    'woocommerce_cart_item_remove_link',
    sprintf(
        '<a href="%s" class="remove1" aria-label="%s" data-product_id="%s" data-cart_item_key="%s" data-product_sku="%s">&times;</a>',
        esc_url( wc_get_cart_remove_url( $cart_item_key ) ),
        esc_attr__( 'Remove this item', 'woocommerce' ),
        esc_attr( $product_id ),
        esc_attr( $cart_item_key ),
        esc_attr( $_product->get_sku() )
    ),
    $cart_item_key
);
?>

但我不知道如何通过 ajax 运行命令而不是刷新页面。我试图修改我发现的关于使用 ajax 添加到购物车的代码。

没用,页面还在刷新。

这是我尝试过的:

$(document).on('click', '.remove1', function (e) {
e.preventDefault();
var $thisbutton = $(this),
        $form = $thisbutton.closest('form.cart'),
        id = $thisbutton.val(),
        product_qty = $form.find('input[name=quantity]').val() || 1,
        product_id = $form.find('input[name=product_id]').val() || id,
        variation_id = $form.find('input[name=variation_id]').val() || 0;

var data = {
    action: 'woocommerce_cart_item_removed',
    product_id: product_id,
    product_sku: '',
    quantity: product_qty,
    variation_id: variation_id,
};


$.ajax({
    type: 'post',
    url: wc_add_to_cart_params.ajax_url, // What params should I use?
    data: data,
    beforeSend: function (response) {
        $thisbutton.removeClass('added').addClass('loading');
    },
    complete: function (response) {
        $thisbutton.addClass('added').removeClass('loading');
    },
    success: function (response) {

        if (response.error && response.product_url) {
            window.location = response.product_url;
            return;
        }
    },
});
});

functions.php

add_action( 'woocommerce_remove_cart_item', 'update_cart', 10, 2 );

function update_cart(){
  //What to do here?
}

没有调试错误。

我没有在网上找到一些重要的信息:

  • 我应该使用哪个 ajax url url: wc_add_to_cart_params.ajax_url 从迷你购物车中删除商品?
  • 如何处理从ajax传输到functions.php的数据?

如何使用 ajax 从 Woocommerce 迷你购物车中删除商品?

【问题讨论】:

    标签: javascript php jquery wordpress woocommerce


    【解决方案1】:

    首先,请检查您的 WooCommerce 设置以查看 Ajax 是否启用了添加到购物车按钮。如果没有,请从管理面板启用它。查看截图click here to see the screenshot of admin panel setting for ajax

    然后尝试从购物车中删除产品。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 2016-12-29
      • 2017-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      相关资源
      最近更新 更多