-
-
Save FrancoStino/a49356f88e41d2e5aca10ee8ec2be369 to your computer and use it in GitHub Desktop.
Prevents the Addition of A Product if There Is a Specific Product in The cart, While Emptying the Basket Leaving the Specific Product if It Is Added - Woocommerce
This file contains hidden or 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
<?php | |
// Funzione che controlla se nel carrello c'è un prodotto specifico | |
add_filter( 'woocommerce_add_to_cart_validation', 'prevent_product_add_to_cart', 10, 3 ); | |
function prevent_product_add_to_cart( $passed, $product_id, $quantity ) { | |
// set the product IDs that will prevent the addition of new products | |
$restricted_products = array( 1291 ); | |
// check if any of the restricted products are already in the cart | |
foreach( WC()->cart->get_cart() as $cart_item ) { | |
if( in_array( $cart_item['product_id'], $restricted_products ) ) { | |
// if a restricted product is in the cart, do not allow new products to be added | |
wc_add_notice( __( 'Poichè nel tuo carrello esiste il pacchetto completo dei corsi, non sarà possibile procedere.', 'woocommerce' ), 'error' ); | |
return false; | |
} | |
} | |
// if a restricted product is not already in the cart, allow new products to be added | |
return $passed; | |
} | |
add_action( 'woocommerce_add_to_cart', 'check_for_restricted_products_in_cart' ); | |
// Funzione che previene l'aggiunta di un prodotto se nel carrello c'è un prodotto specifico | |
function check_for_restricted_products_in_cart() { | |
// set the product ID that will trigger the removal of all non-restricted products from the cart | |
$restricted_product = 1291; | |
// check if the restricted product is in the cart | |
$restricted_product_in_cart = false; | |
foreach( WC()->cart->get_cart() as $cart_item ) { | |
if( $cart_item['product_id'] == $restricted_product ) { | |
$restricted_product_in_cart = true; | |
break; | |
} | |
} | |
// if the restricted product is in the cart, remove all non-restricted products and show a notice | |
if( $restricted_product_in_cart ) { | |
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { | |
if( ! in_array( $cart_item['product_id'], array( $restricted_product ) ) ) { | |
WC()->cart->remove_cart_item( $cart_item_key ); | |
} | |
} | |
wc_add_notice( __( 'I corsi singoli sono stati rimossi dal carrello.', 'woocommerce' ), 'notice' ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment