Categories

Monday, November 18, 2024
#919814419350 therichposts@gmail.com
WoocommerceWoocommerce HooksWordpressWordpress Hooks

Set a minimum order quantity for a specific product in WooCommerce using hooks

Set a minimum order quantity for a specific product in WooCommerce using hooks

Hello guys how are you? Welcome back to my blog. Guys today in this blog post I will tell you Set a minimum order quantity for a specific product in WooCommerce using hooks.
To achieve this, you can use the woocommerce_add_to_cart_validation hook to enforce the minimum order quantity on the cart page and display an error if the quantity is below the required limit.

Here’s an example code snippet that sets a minimum order quantity of 10 for a particular product:

function custom_minimum_order_quantity( $passed, $product_id, $quantity ) {
    // Set the product ID you want to enforce the minimum order quantity for
    $target_product_id = 123; // Replace with your actual product ID

    // Set the minimum quantity
    $minimum_quantity = 10;

    // Check if the product is the target product and if the quantity is less than the minimum
    if ( $product_id == $target_product_id && $quantity < $minimum_quantity ) {
        // Display an error message and prevent adding to cart
        wc_add_notice( sprintf(
            'You must order at least %s of this product.',
            $minimum_quantity
        ), 'error' );
        $passed = false;
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'custom_minimum_order_quantity', 10, 3 );

Instructions:

  1. Add this code to your theme’s functions.php file or use a custom plugin.
  2. Replace 123 with the actual product ID for which you want to set the minimum quantity.
  3. Modify $minimum_quantity if you want to change the minimum required amount.

This will enforce a minimum order quantity of 10 for the specified product. If a user tries to add fewer than 10 of that product to the cart, they’ll see an error message.

Let me know if you need any adjustments! Feel free to comment below.

Ajay

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.