Search code examples
phpwoocommercesubscriptionwoocommerce-subscriptions

WooCommerce subscription status get issue


I am using a function in function.php of theme:

I am checking that at login, if user has not active subscription than it should redirect to a page. I have two users, one has active subscription and other has expired. But when I use this code for both users, both are going in the else condition, which means no subscription.

It's not a product subscription, it's a subscription for user's plans.

$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 (!empty($active_subscriptions)) {
    echo "1";
    die;
    return true;
} else {
    echo "2";
    die;
}

Solution

  • You can try using the wcs_get_subscriptions function.

    $subscriptions = wcs_get_subscriptions(
        array(
            'customer_id' => $user_id,
            'subscription_status' => 'wc-active',
            'subscriptions_per_page' => - 1
        )
    );