限制woocommerce篮子大小

时间:2015-10-14 20:09:10

标签: php wordpress wordpress-plugin 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' );
    }
}
}

1 个答案:

答案 0 :(得分: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 );