Hi. How can we help?

Subscription - How limit the users to have only one active subscription per product on same time ?

With subscription plugin, a user can purchase the same subscription several time in different order.
If you want limit this, try to add this custom code in your functions.php

if( class_exists('YITH_WC_Subscription') && class_exists( 'YWSBS_Subscription_Helper' ) ) {


if ( ! function_exists( 'ywsbs_check_customer_bought_product' ) ) {
add_filter( 'woocommerce_add_to_cart_validation', 'ywsbs_check_customer_bought_product', 10, 4 );
function ywsbs_check_customer_bought_product( $valid, $product_id, $quantity, $variation_id = 0 ) {
$id = ( $variation_id ) ? $variation_id : $product_id;
if ( YITH_WC_Subscription()->is_subscription( $id ) ) {
$current_user = wp_get_current_user();
// determine if customer has bought product
$subscription_status = ywsbs_customer_bought_product_on_subscription( $product_id, $current_user->ID );
if ( $current_user && ( $subscription_status != '' && 'cancelled' !== $subscription_status ) ) {
$message = __( 'This subscription has been removed from your cart. You have already purchased this product', 'yith-woocommerce-subscription' );
wc_add_notice( $message, 'notice' );

return false;
}
}

return $valid;
}
}

if ( ! function_exists( 'ywsbs_customer_bought_product_on_subscription' ) ) {
function ywsbs_customer_bought_product_on_subscription( $product_id, $user_id ) {

$subscriptions_users = YWSBS_Subscription_Helper()->get_subscriptions_by_user( $user_id );
$status = '';
if ( ! empty( $subscriptions_users ) ) {
foreach ( $subscriptions_users as $subscription_post ) {
$subscription = ywsbs_get_subscription( $subscription_post->ID );
if ( $subscription->get( 'product_id' ) == $product_id ) {
$status = $subscription->get( 'status' );
break;
}
}
}

return $status;
}
}
}

 

Was this article helpful?
0 out of 1 found this helpful

Back to Help Center >