Created
January 22, 2024 03:08
-
-
Save shaunkuschel/83797c170a1286875b0b3a705b087e88 to your computer and use it in GitHub Desktop.
Force "Sold Individually" to work with Product Add-Ons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
add_filter( 'woocommerce_bundle_before_validation', 'check_if_bundled_item_exists_in_cart', 10, 2 ); | |
function check_if_bundled_item_exists_in_cart( $is_valid, $bundle ) { | |
$bundled_items = $bundle->get_bundled_items(); | |
foreach ( $bundled_items as $bundled_item ) { | |
$is_valid = check_if_product_exists_in_cart( $is_valid, $bundled_item->get_product_id() ); | |
if ( ! $is_valid ) { | |
break; | |
} | |
} | |
return $is_valid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment