Skip to content

Instantly share code, notes, and snippets.

@jasubal
Last active January 15, 2024 10:08
Show Gist options
  • Select an option

  • Save jasubal/d1266a94f10cdb6167dce3add21f14b3 to your computer and use it in GitHub Desktop.

Select an option

Save jasubal/d1266a94f10cdb6167dce3add21f14b3 to your computer and use it in GitHub Desktop.
woo One product per type only
<?php
add_filter( 'woocommerce_add_to_cart_validation', 'limit_product_quantity_in_cart', 10, 3 );
function limit_product_quantity_in_cart( $passed, $product_id, $quantity ) {
if ( $quantity > 1 ) {
wc_add_notice( __( 'Only a quantity of one is allowed per product.', 'domain' ), 'error' );
return false;
}
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['product_id'] == $product_id || ( isset( $cart_item['variation_id'] ) && $cart_item['variation_id'] == $product_id ) ) {
wc_add_notice( __( 'This product is already in your cart. Only a quantity of one is allowed per product.', 'domain' ), 'error' );
return false;
}
}
return $passed;
}
@jasubal
Copy link
Author

jasubal commented Jan 15, 2024

This Filter does the following:
-Attaches to WooCommerce Add to Cart Validation: Uses the woocommerce_add_to_cart_validation filter to validate the add-to-cart process.
-Checks Quantity Being Added: If the quantity is more than one, it displays an error message and prevents the addition.
-Iterates Through Cart Items: Loops through each item in the cart.
-Checks for Product or Variation in Cart: If the product or its variation is already in the cart, it displays an error message and prevents adding the same product again.
-Returns the Validation Result: Returns true if the product can be added (i.e., not in the cart and quantity is one) or false if the conditions are not met.
-Replace 'domain' with your theme's text domain for proper internationalization of the error messages. This code ensures that the site doesn't hang when a product is added to the cart and that only one quantity of each product is allowed. If you still encounter issues after implementing this solution, it might be related to other aspects of your WooCommerce setup or conflicts with themes/plugins, and further investigation would be required.
add_filter( 'woocommerce_add_to_cart_validation', 'limit_product_quantity_in_cart', 10, 3 );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment