【问题标题】:Remove variable product from cart with ajax in woocommerce在woocommerce中使用ajax从购物车中删除可变产品
【发布时间】:2017-01-10 05:01:47
【问题描述】:

我已成功实施此代码以使用 Ajax 从购物车中删除产品。但它不适用于可变乘积。

/**
 * Remove Cart via Ajax
 */
function product_remove() {
    global $wpdb, $woocommerce;
    session_start();
    $cart = WC()->instance()->cart;
    $id = $_POST['product_id'];
    $cart_id = $cart->generate_cart_id($id);
    $cart_item_id = $cart->find_product_in_cart($cart_id);
    if($cart_item_id){
       $cart->set_quantity($cart_item_id,0);
    }
}
add_action( 'wp_ajax_product_remove', 'product_remove' );
add_action( 'wp_ajax_nopriv_product_remove', 'product_remove' );

也许我需要将 $variation_id 传递给 $cart_id 但我不知道该怎么做。

【问题讨论】:

  • 当我尝试删除购物车中的可变产品时也出现错误:PHP 警告:call_user_func_array() 期望参数 1 是有效的回调,没有给出数组或字符串

标签: php jquery ajax wordpress woocommerce


【解决方案1】:

使用$cart_item_key 而不是$product_id 在购物车上创建链接。

然后,在服务器端,您不需要使用$cart->generate_cart_id($id); 方法,因为您已经拥有它。

查看适合我的示例:

一、购物车的创建:

// This is the logic that create the cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { ?>
    <li class="<?php echo esc_attr( apply_filters( 'woocommerce_mini_cart_item_class', 'mini_cart_item', $cart_item, $cart_item_key ) ); ?>">
        // Remove product link
        <a href="#" onclick="return js_that_call_your_ajax(this);" data-product_id="<?php echo esc_attr( $cart_item_key ); ?>">&times;</a>
        // Other product info goes here...
    </li>
<?php }

现在服务器端的修改:

/**
 * Remove Cart via Ajax
 */
function product_remove() {
    global $wpdb, $woocommerce;
    session_start();
    $cart = WC()->instance()->cart;
    $cart_id = $_POST['product_id']; // This info is already the result of generate_cart_id method now
    /* $cart_id = $cart->generate_cart_id($id); // No need for this! :) */
    $cart_item_id = $cart->find_product_in_cart($cart_id);
    if($cart_item_id){
       $cart->set_quantity($cart_item_id,0);
    }
}
add_action( 'wp_ajax_product_remove', 'product_remove' );
add_action( 'wp_ajax_nopriv_product_remove', 'product_remove' );

这对我来说很好用!

【讨论】:

    猜你喜欢
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 2018-08-22
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多