Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This code snippet for WooCommerce Subscriptions will only allow a single purchased subscription across all subscription products for customers.
add_filter('woocommerce_add_to_cart_validation', 'check_num_of_subscriptions', 10, 2);
function check_num_of_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) {
// alternative use: $has_sub = wcs_user_has_subscription( '', '', 'active' );
if ( has_active_subscription() ) {
// cart validation must fail, because user is not allowed to have multiple subscriptions
wc_clear_notices();
wc_add_notice(__('You already have an active subscription.', 'woocommerce'), 'error');
return false;
} else {
return true;
}
}
return $valid;
}
function has_active_subscription()
{
$user_id = get_current_user_id();
$active_subscriptions = get_posts(array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => $user_id,
'post_type' => 'shop_subscription',
'post_status' => 'wc-active'
));
if (!empty($active_subscriptions))
return true;
else
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment