简体   繁体   English

Woocommerce - 从购物车中仅删除一件产品

[英]Woocommerce - Remove Only one Unit of a product from cart

I am working on this woocommerce search function that uses AJAX to fetch products on every keystroke and that gives the possibility to add or remove units of a certain product to cart right from the instant search results modal.我正在研究这个 woocommerce 搜索功能,它使用 AJAX 在每次击键时获取产品,并且可以直接从即时搜索结果模式添加或删除特定产品的单位到购物车。

In each search result there is this group of two buttons that allow the client to add 1 or remove 1 product from cart at a time.在每个搜索结果中都有这组两个按钮,允许客户一次从购物车中添加 1 个或从购物车中删除 1 个产品。 I managed to make the add to cart button work but can't seem to find a good solution to remove just one single unit from cart instead of all of them at once.我设法使添加到购物车按钮起作用,但似乎无法找到一个好的解决方案来从购物车中只删除一个单元而不是一次删除所有单元。

在此处输入图像描述

I have tried this:我试过这个:

function remove_product_from_cart_programmatically() {
   if ( is_admin() ) return;
   $product_id = 282;
   $product_cart_id = WC()->cart->generate_cart_id( $product_id );
   $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
   if ( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );
}

but it removes all products with that ID at once.但它会立即删除所有具有该 ID 的产品。

I want to be able to remove unit by unit in case there are items in cart with that ID.我希望能够逐个单元地移除,以防购物车中有具有该 ID 的物品。

This is the code I have right now for the remove from cart button:这是我现在用于从购物车按钮中删除的代码:

add_action('wp_ajax_search_remove_from_cart', 'search_remove_from_cart');
add_action('wp_ajax_nopriv_search_remove_from_cart', 'search_remove_from_cart');

// handle the ajax request
function search_remove_from_cart()
{
    $product_id = $_REQUEST['product_id'];
    WC()->cart->remove_cart_item($product_id);

    $products_in_cart = WC()->cart->get_cart_item_quantities($product_id);
    $updated_qty = $products_in_cart[$product_id];

    // in the end, returns success json data
    wp_send_json_success(["Product removed from cart Successfuly!", $updated_qty]);

    // or, on error, return error json data
    wp_send_json_error(["Could not remove the product from cart"]);
}

Is there any function to remove only one unit of a certain product from cart?是否有任何功能可以从购物车中仅删除一个特定产品的单位?

Thank you all !谢谢你们 !

You have to change the quantity instead of removing the product.您必须更改数量而不是移除产品。 Number of product units in the cart = quantity.购物车中的产品数量 = 数量。

Try something like this:尝试这样的事情:

function remove_from_cart(){
    if ( is_admin() ) return;
    $product_id = 47;
    $cart = WC()->cart;
    $product_cart_id = $cart->generate_cart_id( $product_id );
    $cart_item_key = $cart->find_product_in_cart( $product_cart_id );
    if ( $cart_item_key ){
        $quantity = $cart->get_cart_item($cart_item_key)['quantity'] - 1;
        $cart->set_quantity($cart_item_key, $quantity);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM