php - 限制 woocommerce 购物篮大小

标签 php wordpress woocommerce

下面有一个片段,将 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' );
    }
}
}

最佳答案

每个产品都必须经过验证才能添加到购物车。您可以通过 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 );

关于php - 限制 woocommerce 购物篮大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33134668/

相关文章:

wordpress - 如何从购物车、结账和单一产品页面中删除 Woocommerce 侧边栏?

php - 根据 WooCommerce 统一费率运输方法的自定义字段计算添加交货时间

php - 使用不同域对网站进行负载平衡

javascript - 如何在第一次更新 'X' 分钟后更改字段值

PHP用分号替换第一个空格

wordpress - 我将如何扩展木材以便能够使用 handle 作为包含中的引用?

javascript - YouTube 嵌入 WordPress - 高度问题

wordpress - 在 WordPress 中添加菜单项

连接父列并具有多个内部连接的mysql查询

php - 高效重复访问第三方网站