WooCommerce Subscriptions is a great tool for managing recurring payments, but by default, it doesn’t restrict users to just one active subscription at a time. If you want to ensure that customers can only have one active subscription, follow this simple guide.
Step 1: Add Code to functions.php
To enforce this restriction, insert the following code into your active theme’s functions.php
file. Ideally, use a child theme to prevent losing changes when updating your theme.
<?php
add_filter('woocommerce_add_to_cart_validation', 'restrict_multiple_subscriptions', 10, 2);
function restrict_multiple_subscriptions($valid, $product_id) {
$product_to_add = wc_get_product($product_id);
if ($product_to_add instanceof WC_Product_Subscription || $product_to_add instanceof WC_Product_Variable_Subscription) {
if (user_has_active_subscription()) {
wc_add_notice('You can only have one active subscription at a time.', 'error');
return false; // Prevents adding another subscription
}
}
return $valid;
}
function user_has_active_subscription() {
$user_id = get_current_user_id();
$active_subscriptions = get_posts([
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => $user_id,
'post_type' => 'shop_subscription',
'post_status' => 'wc-active'
]);
return !empty($active_subscriptions);
}
?>
Step 2: How This Works
- Hooking into WooCommerce: The
add_filter
function modifies WooCommerce behavior by hooking intowoocommerce_add_to_cart_validation
, which runs when a user adds a product to their cart. - Checking the Product Type: The
restrict_multiple_subscriptions
function verifies if the added product is a subscription product. - Validating Active Subscriptions: The
user_has_active_subscription
function checks if the user already has an active subscription. - Blocking Additional Subscriptions: If an active subscription exists, WooCommerce prevents the new one from being added and displays an error message.
Step 3: Testing the Feature
To ensure the code works correctly:
- Try adding a subscription product to the cart as a test user.
- Attempt to add another subscription while the first one is still active.
- WooCommerce should display an error message and block the second subscription.
Conclusion
This simple code snippet ensures that customers can only have one active subscription at a time. It improves user experience by preventing accidental multiple subscriptions and simplifies subscription management for store owners.
By making this small customization, you can enforce a one-subscription rule without relying on additional plugins. If you need further customizations, consider hiring a developer or exploring WooCommerce’s documentation for advanced options.
Need help implementing this? Let us know in the comments!