如何根据Woocommerce中的条件从购物车中删除商品

时间:2016-11-24 06:05:00

标签: php wordpress woocommerce cart hook-woocommerce

我正在一个网站上的不同餐厅工作。不同的餐厅有不同的菜单。但条件是一个人可以从最大的一家餐厅订购。因此,如果他输入KFC restaurant并订购商品,那么他决定不从KFC获取食物,然后转到Macdonalds页面。并订购6件商品。

现在购物车中有7件商品(一件来自肯德基,另外六件来自MADONALDS)。但条件是,一个人只能从最多1个餐厅订购,所以我需要删除从KFC Restaurant添加的菜单。

为了简化此任务,我在woocommerce restaurant_id中引入了cart_item_data参数。所以我有两件事让它更容易 -

  

(1) $current_restaurant_id - 当前的餐馆ID(在其上   页面i /您目前正在入住)
和(2)restaurant_id in   cart_item_data;

差不多完成了,但问题出现在最后一刻:

我的代码在这里:

global $woocommerce;
$items = $woocommerce->cart->get_cart();
$current_restaurant_id = get_the_ID();
foreach($items as $item => $values) { 
    if($current_restaurant_id !== $values['restaurant_id']){
        WC()->cart->remove_cart_item($values['product_id']);
    }else{
        $_product = $values['data']->post; 
        $price = get_post_meta($values['product_id'] , '_price', true);
        $output = '<li class="clearfix">';
        $output .= '<span class="pull-left">'. $_product->post_title .' ('. $values['quantity'] . ') ' . $values['restaurant_id'] . '</span>';
        $output .= '<span class="pull-right text-spl-color">'. $price*$values['quantity'] .'</span>';
        $output .= '</li>';
        echo $output;
    }
}

购物车上没有任何商品,但物品在购物车中。没有项目被删除。

1 个答案:

答案 0 :(得分:2)

以下是WooCommerce购物车对象的正确代码...要从购物车中删除商品,您必须使用密钥,而不是价值......我唯一无法测试的是您的“restaurant_id”。所有其他代码都经过测试并且功能齐全。

以下是此代码:

$current_restaurant_id = get_the_ID();
foreach(WC()->cart->get_cart() as $key => $item) {
    $item_id = $item['product_id']; // the product ID
    $variation_id = $item['variation_id']; // if is a variable product, this is going to be > 0
    $item_price = $item['data']->price; // the price of the product
    if($current_restaurant_id !== $item['restaurant_id'])
    {
        WC()->cart->remove_cart_item($key);
    }
    else
    {
        echo '<li class="clearfix">
        <span class="pull-left">'. $item['data']->post->post_title .' ('. $item['quantity'] . ') ' . $item['restaurant_id'] . '</span>
        <span class="pull-right text-spl-color">'. $item['line_total'] .'</span>
        </li>';
    }
}

之后,我不知道你在哪里使用这段代码,或者你是否在钩子函数中使用它,所以我无法帮助...