For WooCommerce subscriptions I haven't found any function to check if the current user has an active subscription.
So I have made this answer that still works on WooCommerce 3+ and last WC Subscriptions plugin: Detecting if the current user has an active subscription
So using a custom function hooked in woocommerce_add_to_cart action hook and using my conditional function code from my old answer, you will get it working:
// Conditional function detecting if the current user has an active subscription
function has_active_subscription( $user_id=null ) {
// if the user_id is not set in function argument we get the current user ID
if( null == $user_id )
$user_id = get_current_user_id();
// Get all active subscrptions for a user ID
$active_subscriptions = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => $user_id,
'post_type' => 'shop_subscription', // Subscription post type
'post_status' => 'wc-active', // Active subscription
) );
// if user has an active subscription
if(!empty($active_subscriptions)) return true;
else return false;
}
// Conditionally checking and adding your subscription when a product is added to cart
add_action( 'woocommerce_add_to_cart', 'add_subscription_to_cart', 10, 6 );
function add_subscription_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
// Here define your subscription product
$subscription_id = 2282;
$found = false;
if ( is_admin() || has_active_subscription() || $product_id == $subscription_id ) return; // exit
// Checking if subscription is already in cart
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['product_id'] == $subscription_id ){
$found = true;
break;
}
}
// if subscription is not found, we add it
if ( ! $found )
WC()->cart->add_to_cart( $subscription_id );
}
Code goes in any plugin php file (hooks can be used in function.php file of the active theme).
The code is tested and works.
And if the subscription is removed from cart, we will do a re-check in checkout:
add_action( 'woocommerce_before_checkout_form', 'check_subscription_in_checkout', 10, 0 );
function check_subscription_in_checkout() {
// Here define your subscription product
$subscription_id = 2282;
$found = false;
if ( is_admin() || has_active_subscription() || ! is_checkout() ) return; // exit
// Checking if subscription is already in cart
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['product_id'] == $subscription_id ){
$found = true;
break;
}
}
// if subscription is not found, we add it
if ( ! $found )
WC()->cart->add_to_cart( $subscription_id );
}