kreamweb
6/3/2016 - 11:26 AM

add only a product in the cart if subscription is installed

add only a product in the cart if subscription is installed



if ( class_exists( 'YITH_WC_Subscription' ) ) {

	remove_filter( 'woocommerce_add_to_cart_validation', array( YITH_WC_Subscription(), 'cart_item_validate' ), 11 );
 	add_filter( 'woocommerce_add_to_cart_validation', 'ywsbs_cart_item_validate', 10, 4 );

	/**
	 * Only a product can be added to the cart this method check if there's
	 * a product in cart and remove the element present in cart
	 *
	 * @param $valid        bool
	 * @param $product_id   int
	 * @param $quantity     int
	 * @param $variation_id int
	 *
	 * @return bool
	 * @since  1.0.0
	 */

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

		if( ! $valid ){
			return $valid;
		}

		if ( WC()->cart->get_cart_contents_count() ) {
			WC()->cart->empty_cart();
			$message = __( 'You cannot purchase different products at the same time.', 'your-text-domain' );
			wc_add_notice( $message, 'notice' );
		}

		return $valid;
	}
}