Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Limit the Maximum Quantity of Products via Custom Field in WooCommerce?

This customization is ideal for online stores to restrict the total quantity of variable and simple products in WooCommerce using a custom field introduced on the admin side. This way you can control the maximum quantity customers can purchase. Let’s look into how the code works:

  • Firstly, it adds a custom field, _max_qty to the inventory tab in the product data meta box.
  • Saves the custom field value for products during the product update process.
  • Checks the cart items for the maximum quantity specified in the custom field.
  • If the quantity exceeds the specified limit, it displays an error notice to the customer.


// Adds custom field to the inventory tab in the product data meta box
function ts_action_woocommerce_product_options_stock_status() {        
    woocommerce_wp_text_input(
        array(
            'id'                => '_max_qty',
            'placeholder'       => __( 'Set the bundle maximum to at least 2 items or leave blank', 'woocommerce' ),
            'label'             => __( 'Maximum Quantity', 'woocommerce' ),
            'desc_tip'          => true,
            'description'       => __( 'Limits the maximum amount of product your customer can order', 'woocommerce' ),
            'type'              => 'number',
            'custom_attributes' => array(
                'step' => 'any',
            ),
        )
    );
}
add_action( 'woocommerce_product_options_stock_status', 'ts_action_woocommerce_product_options_stock_status', 10, 0 );

// Save custom field to the inventory tab in the product data meta box
function ts_action_woocommerce_admin_process_product_object( $product ) {
    // Isset
    if ( isset( $_POST['_max_qty'] ) ) {        
        // Update
        $product->update_meta_data( '_max_qty', sanitize_text_field( $_POST['_max_qty'] ) );
    }
}
add_action( 'woocommerce_admin_process_product_object', 'ts_action_woocommerce_admin_process_product_object', 10, 1 );

// Function to get cart quantity for a variable product
function ts_get_cart_quantity_variable_product( $child_ids ) { 
    $cart_item_quantities = WC()->cart->get_cart_item_quantities();
    $qty = 0;
    foreach ( $child_ids as $child_id ) {
        if ( array_key_exists( $child_id, $cart_item_quantities ) ) {
            $qty += $cart_item_quantities[$child_id];
        }
    }
    return $qty;
}

// Check cart items to ensure the maximum quantity is not exceeded
function ts_action_woocommerce_check_cart_items() {    
    $i = 0;
    $bad_products = array();
    $already_checked = array();
    
    foreach( WC()->cart->get_cart() as $cart_item ) {
        $product_id = $cart_item['product_id'];
        $variation_id = $cart_item['variation_id'];
        
        if ( ! in_array( $product_id, $already_checked ) ) {            
            $already_checked[] = $product_id;
            
            $product = $variation_id > 0 ? wc_get_product( $product_id ) : $cart_item['data'];
            $max_qty = $product->get_meta( '_max_qty', true );
            
            if ( ! empty( $max_qty ) && $max_qty > 0 ) {               
                $cart_qty = $cart_item['quantity'];
                
                if ( $product->get_type() == 'variable' ) {                 
                    $child_ids = $product->get_children();
                    $cart_qty = ts_get_cart_quantity_variable_product( $child_ids );               
                }
                
                if ( $cart_qty > $max_qty ) {
                    $bad_products[$i]['product_id'] = $product_id;
                    $bad_products[$i]['in_cart'] = $cart_qty;
                    $bad_products[$i]['max_req'] = $max_qty;
                    $i++;
                }
            }
        }
    }
    
    if ( is_array( $bad_products) && count( $bad_products ) > 0 ) { 
        wc_clear_notices();
        
        foreach( $bad_products as $bad_product ) {
            wc_add_notice( sprintf(
                __( '%s has a maximum quantity of %d. You currently have %d in cart', 'woocommerce' ),
                get_the_title( $bad_product['product_id'] ),
                $bad_product['max_req'],
                $bad_product['in_cart']
            ), 'error' );
        }
        
        // Optional: remove proceed to checkout button
        remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
    }
}   
add_action( 'woocommerce_check_cart_items' , 'ts_action_woocommerce_check_cart_items', 10, 0 );

Output

As described in the code working flow process, the new custom field is created in the admin backed. To set the quantity for a specific product you need to follow the steps given below.

How to Limit the Maximum Quantity of Products via Custom Field in WooCommerce? - Tyche Softwares


  • Go to Products >All Products >Click on a product to view the product edit page for a specific product.
  • In the product data meta box, go to the “Inventory” tab.
  • You should see a new field labeled “Maximum Quantity”
  • Enter a numerical value to set the maximum quantity for the product.
  • Update or save the product.

When the user adds a variable or simple product to the cart, the function loops through the cart items, and checks for the maximum quantity set (for e.g. 2) for that product from the meta field in the admin area. If the user adds 5 of the total variations, the code will detect that the total exceeds the specified minimum of (2).An error notice is displayed indicating that the variable product has a maximum quantity of 2, and the user currently has 6 in the cart. Additionally, the ‘Proceeed to Checkout’ button is removed in order to avoid users to continue their checkout process.


How to Limit the Maximum Quantity of Products via Custom Field in WooCommerce? - Tyche Softwares

Similar to the above illustration, the maximum quantity is limited for simple products as well by setting the maximum limit in the custom field.

How to Limit the Maximum Quantity of Products via Custom Field in WooCommerce? - Tyche Softwares

Alternatively, you can also limit the products based on the usage limit of the user. Check here on how to limit free products for user when offering bogo buy one get one offers in WooCommerce.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x