Skip to content

Instantly share code, notes, and snippets.

@marcbovet
Last active August 19, 2018 20:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcbovet/89cfcd2bee451e15c9e0a10267f3d7cd to your computer and use it in GitHub Desktop.
Save marcbovet/89cfcd2bee451e15c9e0a10267f3d7cd to your computer and use it in GitHub Desktop.
// Woocommerce
// Restrict customer to buy in only one shop
add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart_with_variations' );
function woo_custom_add_to_cart_with_variations( $cart_item_data ) {
//Compliant with product-variations
//Tested with woocoommerce 3.1 | WC Vendors PRO 1.4.3
global $woocommerce;
$items = $woocommerce->cart->get_cart(); //getting cart items
$_product = array();
foreach($items as $item => $values) {
$product_id_in_cart = $values['data']->id;
$_product[] = $values['data'];
break; //after 1st product we can stop the loop
}
if(isset($product_id_in_cart)){
//GET VENDOR ID OF FIRST PRODUCT IN CART
$product_in_cart_vendor_id = get_post_field( 'post_author', $product_id_in_cart); //get vendor id from cart.
//GET LAST PRODUCT ADDED TO CART
$product_id_added = (int) apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_REQUEST['add-to-cart']));
//GET VENDOR ID OF LAST PRODUCT ADDED IN CART
$product_added_vendor_id = get_post_field( 'post_author', $product_id_added );
//CHECK IF BOTH VENDOR IDs ARE EQUAL
//TODO : ask user if he wants to empty his cart.
if( $product_in_cart_vendor_id !== $product_added_vendor_id ){$woocommerce->cart->empty_cart();wc_add_notice( __('You can order only from 1 restaurant!', 'swiss_takeaway'),'error');}
return $cart_item_data; }
}
@Arthi22
Copy link

Arthi22 commented Aug 19, 2018

Dear Marc, The codeing is very useful. but the error message is not displaying for me. Can you help me. I using Wc vendors version Version 2.1.0 and woocommerce Version 3.4.4

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