Skip to content

Instantly share code, notes, and snippets.

@woogists
Created December 29, 2023 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woogists/342ad7b0867d958bc3d7ec9d3e20a8aa to your computer and use it in GitHub Desktop.
Save woogists/342ad7b0867d958bc3d7ec9d3e20a8aa to your computer and use it in GitHub Desktop.
[Product Add-ons] Allow one instance of Sold Individually products in the cart, even if they have different add-ons selected
<?php
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_product_exists_in_cart', 10, 2 );
function check_if_product_exists_in_cart( $is_valid, $product_id ) {
$product = wc_get_product( $product_id );
if ( $product->is_sold_individually() ) {
$cart_contents = WC()->cart->get_cart_contents();
foreach ( $cart_contents as $cart_item ) {
if ( $product_id === $cart_item[ 'product_id' ] ) {
$is_valid = false;
$notice = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', wc_get_cart_url(), __( 'View cart', 'woocommerce' ), sprintf( __( 'You cannot add another "%s" to your cart.', 'woocommerce' ), $product->get_name() ) );
wc_add_notice( $notice, 'error' );
break;
}
}
}
return $is_valid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment