【问题标题】:Checkout with a single product: verify if ANY product is in the cart, and give error使用单个产品结帐:验证购物车中是否有任何产品,并给出错误
【发布时间】:2015-01-17 19:02:10
【问题描述】:

我无法想象如何验证购物车内是否有一些产品。我只需要允许一个产品进行结帐。

这是 class-wc-cart.php 中使用的代码,用于防止在购物车中已经有相同的产品时添加产品,我确信应该非常相似,但我缺少一些 WP 变量定义任何类型的产品。 我也试过this code,但它在functions.php中不起作用(不,我没有使用子主题)。

if ( $product_data->is_sold_individually() ) {
            $in_cart_quantity = $cart_item_key ? $this->cart_contents[ $cart_item_key ]['quantity'] : 0;

            // If it's greater than 0, it's already in the cart
            if ( $in_cart_quantity > 0 ) {
                wc_add_notice( sprintf(
                    '<a href="%s" class="button wc-forward">%s</a> %s',
                    $this->get_cart_url(),
                    __( 'View Cart', 'woocommerce' ),
                    sprintf( __( 'You cannot add another &quot;%s&quot; to your cart.', 'woocommerce' ), $product_data->get_title() )
                ), 'error' );
                return false;
            }
        }

谢谢。

【问题讨论】:

标签: php wordpress woocommerce e-commerce shopping-cart


【解决方案1】:

不要直接在 woocommerce 核心文件中进行更改,因为当您更新插件时,您的代码可能会丢失。

将以下代码添加到functions.php中,它只会将一种产品添加到购物车中:

add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_cart_item_data_custom' );

function woocommerce_add_cart_item_data_custom( $cart_item_data ) {

    global $woocommerce;
    if($woocommerce->cart->cart_contents_count > 0){
         wc_add_notice(
                     __( 'You cannot add another product to your cart.', 'woocommerce' ));

                return false;
    }
}

【讨论】:

  • 这个很好很简单!它有效,但它是如此强大,以至于我无法添加错误消息(比如“嘿,你不能在购物车中添加超过一个产品!”),或者如果没有产品而你也打印出来了第一次重新添加到购物车
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
  • 2016-10-07
相关资源
最近更新 更多