Skip to content

Instantly share code, notes, and snippets.

@kartikparmar
Created June 13, 2020 16:25
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 kartikparmar/d1274fbbeb28dc720bceb9497f823deb to your computer and use it in GitHub Desktop.
Save kartikparmar/d1274fbbeb28dc720bceb9497f823deb to your computer and use it in GitHub Desktop.
Do not allow product to be purchased if particular is present in the cart.
<?php
function wc_purchasable_or_not( $product_id, $status = true ) {
// key : ID of Product where you want to hide Add to Cart.
// value : Array of Product IDs which are present in the cart then hide Add to Cart button for Product ID set in key
$product_check = array(
'2701' => array( '2848', '2563', '1253' ),
'2245' => array( '2848', '2563', '1253' ),
'3998' => array( '2848', '2563', '1253' ),
'4456' => array( '234', '456', '789' ),
'5344' => array( '234', '456', '789' ),
'2365' => array( '234', '456', '789' ),
);
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) { // loop through all the products in the cart
$pro_id = $values['product_id']; // get product id.
foreach( $product_check as $k => $v ) { // looping to check if the product id match with any rule.
if ( in_array( $pro_id, $v ) ) { // if matched.
if ( $k == $product_id ) { // and its rule is for the product id of current product then do not show.
$status = false;
break;
}
}
}
}
return $status;
}
function woocommerce_purchasable_based_on_cart_products( $status, $product ) {
$product_id = $product->get_id();
$status = wc_purchasable_or_not( $product_id );
return $status;
}
add_filter( 'woocommerce_is_purchasable', 'woocommerce_purchasable_based_on_cart_products', 20, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment