php - 如何将特定商品的 WooCommerce 购物车商品数量限制为一个

标签 php wordpress woocommerce cart product-quantity

在我的自定义 Woocommerce 模板中,我想将产品的数量限制为 1。

我在 Empty cart upon page load allowing add to cart in WooCommerce 工作回答我之前的问题。

这就是我所拥有的:

 <?php 
$current_product_id = 5; // The product ID 
$cart               = WC()->cart; // The WC_Cart Object
       $quantity = $cart_item['quantity'];//the quantity
// When cart is not empty 
if ( ! $cart->is_empty() ) {
    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // If the cart item is not the current defined product ID
        if( $current_product_id != $cart_item['product_id'] ) {
            $cart->remove_cart_item( $cart_item_key ); // remove it from cart
        }
}
 if( $quantity >=1) {
    $cart->remove_cart_item( $cart_item_key ); // remove it from cart
 } }}
?>

这有点管用。但我希望在同一页面上结帐,并且使用此代码将产品添加到购物车时结帐不会更新。

最佳答案

要将数量限制为 1,您将使用 WC_cart set_quantity() 方法,如下所示:

<?php 
$current_product_id = 5; // The product ID 
$cart               = WC()->cart; // The WC_Cart Object

// When cart is not empty 
if ( ! $cart->is_empty() ) {
    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // If the cart item is not the current defined product ID
        if( $current_product_id != $cart_item['product_id'] ) {
            $cart->remove_cart_item( $cart_item_key ); // remove it from cart
        } 
        // If the cart item is the current defined product ID and quantity is more than 1
        elseif( $cart_item['quantity'] > 1 ) {
            $cart->set_quantity( $cart_item_key, 1 ); // Set the quantity to 1
        }
    }
}
?>

应该可以。

关于php - 如何将特定商品的 WooCommerce 购物车商品数量限制为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62803763/

相关文章:

php - 以 HTML 形式返回 PHP/MySQL 结果以供编辑

php - 有没有办法将 php 放在 IE 条件注释中

php - WooCommerce - 仅选择一个属性时更改产品图像?

php - 获取列的 MIN 和 MAX 值

php - 删除与 Laravel 5 的一对多关系

wordpress - Yoast 评论 WordPress 中自定义页面的文本

javascript - WordPress 窗口滚动功能不起作用

wordpress - Woocommerce 2.6 API v1 -> 参数无效

wordpress - 显示woocommerce中每位作者的总销售额

php - 在类中访问 session 变量