【问题标题】:Limit woocommerce basket size限制 woocommerce 篮子大小
【发布时间】:2015-10-15 11:23:29
【问题描述】:

我在下面有一个片段,将 woocommerce 订单限制为 5 件商品。当他们尝试使用超过 5 个项目进行结帐时,它会弹出一条消息告诉他们,然后他们必须删除项目。我想知道是否有办法让他们不能将超过 5 个项目添加到购物篮中?

add_action( 'woocommerce_check_cart_items', 'set_max_num_products' );
function set_max_num_products() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
    global $woocommerce;

    // Set the max number of products before checking out
    $max_num_products = 5;
    // Get the Cart's total number of products
    $cart_num_products = WC()->cart->cart_contents_count;

    // A max of 5 products is required before checking out.
    if( $cart_num_products > $max_num_products ) {
        // Display our error message
        wc_add_notice( sprintf( '<strong>A maxiumum of %s samples are allowed per order. Your cart currently contains %s.</strong>',
            $max_num_products,
            $cart_num_products ),
        'error' );
    }
}
}

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    每个产品都必须经过验证才能添加到购物车。您可以通过woocommerce_add_to_cart_validation 过滤器修改验证状态,从而控制是否将其添加到购物车中。

    function so_33134668_product_validation( $valid, $product_id, $quantity ){
        // Set the max number of products before checking out
        $max_num_products = 5;
        // Get the Cart's total number of products
        $cart_num_products = WC()->cart->cart_contents_count;
    
        $future_quantity_in_cart = $cart_num_products + $quantity;
    
        // More than 5 products in the cart is not allowed
        if( $future_quantity_in_cart > $max_num_products ) {
            // Display our error message
            wc_add_notice( sprintf( '<strong>A maxiumum of %s samples are allowed per order. Your cart currently contains %s.</strong>',
                $max_num_products,
                $cart_num_products ),
            'error' );
            $valid = false; // don't add the new product to the cart
        }
        return $valid;
    }
    add_filter( 'woocommerce_add_to_cart_validation', 'so_33134668_product_validation', 10, 3 );
    

    【讨论】:

    • 只是想知道我们可以使用$product_id where $product_id = (int) ( apply_filters( 'woocommerce_add_to_cart_product_id', $_GET['add-to-cart'] ) ? apply_filters( 'woocommerce_add_to_cart_product_id', $_GET['add-to-cart'] ) : apply_filters( 'woocommerce_add_to_cart_product_id', $_POST['add-to-cart'] ) ) ;刚刚添加的产品并限制其数量吗?
    • 不确定你在问什么。
    • 如果我们能检索到刚刚加入购物车的产品及其数量与购物车数量进行比较,让客户知道为什么他不能添加更多产品。这就是我要问的。
    • 这就是我认为我对$future_quantity_in_cart 变量所做的事情。检查尝试添加到购物车的数量($quantity)并将其添加到购物车中的当前商品数量($cart_num_products
    • 您是如何检索 $quantity 的?是否在woocommerce_add_to_cart_validation钩子范围内?
    猜你喜欢
    • 2017-03-26
    • 1970-01-01
    • 2011-12-01
    • 2011-02-14
    • 1970-01-01
    • 2011-11-21
    • 2019-10-26
    • 2016-11-23
    • 1970-01-01
    相关资源
    最近更新 更多