php woocommerce 如何获取单个产品的 $cart_item_key

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20140016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:54:43  来源:igfitidea点击:

woocommerce how to get $cart_item_key for a single product

phpwordpresswordpress-themingwoocommerce

提问by Sarah McLachlane

I'm implementing a Remove Item button next to the add to cart button however I have a problem getting the variable $cart_item_key for a single product. I have the global variables $woocommerce and $product but the only way $cart_item_key is used is a foreach which doesn't help me at all as I need my code to be added in add-to-cart.php.

我在添加到购物车按钮旁边实现了一个删除项目按钮,但是我在获取单个产品的变量 $cart_item_key 时遇到了问题。我有全局变量 $woocommerce 和 $product,但使用 $cart_item_key 的唯一方法是 foreach,它根本没有帮助我,因为我需要将代码添加到 add-to-cart.php 中。

回答by Jobin Jose

You have to set the remove link for each product within loop like this,

您必须像这样在循环中为每个产品设置删除链接,

foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {

 echo $cart_item_key;
 if($cart_item['product_id'] == $your_product_id_to_remove ){
    //remove single product
 }
} 

In any situation you have cart item listing; from that you have to remove, so foreachwill work with your requirement.

在任何情况下,您都有购物车项目列表;您必须从中删除,以便foreach满足您的要求。

Hope its helps..

希望它有帮助..

回答by Sarah McLachlane

This code worked for me. Thanks to Jobin Jose (https://stackoverflow.com/users/1258004/jobin-jose) for the solution!

这段代码对我有用。感谢 Jobin Jose ( https://stackoverflow.com/users/1258004/jobin-jose) 的解决方案!

foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
    if ($cart_item['product_id'] == $product->id ) {
        echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf('<a href="%s" class="remove" title="%s">&times;</a>', esc_url( $woocommerce->cart->get_remove_url( $cart_item_key) ), __( 'Remove this item', 'woocommerce' ) ), $cart_item_key );
}