kreamweb
11/9/2016 - 9:16 AM

1st way: I created 3 variations, the monthly with subscription and the other two just as membership. The problem is that in this way, it is

1st way: I created 3 variations, the monthly with subscription and the other two just as membership. The problem is that in this way, it is possible to add the three variations in the cart, even as the "Sold individually" option is checked.

<?php 


add_filter( 'woocommerce_add_to_cart_validation', 'ywsbs_cart_item_validate', 10, 4 );

function ywsbs_cart_item_validate( $valid, $product_id, $quantity, $variation_id = 0 ){

	$single_subscription = array( 4851, 4852, 4853 );
	$id                  = ( ! empty( $variation_id ) ) ? $variation_id : $product_id;

	//check if in the cart there's a single subscription
	if ( ! in_array( $id, $single_subscription ) ) {
		return $valid;
	}

	$contents = WC()->cart->cart_contents;
	//remove the single subscription that is in the cart
	if ( ! empty( $contents ) ) {
		foreach ( $contents as $item_key => $item ) {
			$product    = $item['data'];
			$current_id = $product->product_type == 'variation' ? $product->variation_id : $product->id;
			if ( in_array( $current_id, $single_subscription ) ) {
				WC()->cart->set_quantity( $item_key, 0 );
				$message = __( 'A subscription has been removed from your cart. You cannot purchase different subscriptions at the same time.', 'yith-woocommerce-subscription' );
				wc_add_notice( $message, 'notice' );
			}
		}
	}

	return $valid;
}