phpwordpresswoocommercemethodswoocommerce-subscriptions

Get and check WooCommerce user subscription end date


How i can display end date subscribe for user ? I have id user and i need date for end subscribe

I try use $WC_Subscription and wcs_get_users_subscriptions($user_id) but this method throws an error.

How I can use $WC_Subscription?


Solution

  • First, wcs_get_users_subscriptions($user_id) is not a method but a function. WC_Subscription is the main Class for subscriptions.

    The main issue in your approach is that wcs_get_users_subscriptions($user_id) function return an array of user subscriptions, but not the subscription object itself, as a user can have multiple subscriptions.

    To get the end date from a WC_Subscription object, you will use get_date('end') method.

    Based on this answer here is the correct way to get, for a user, his subscription's end date, without throwing errors.

    1. You can use a foreach loop to iterate through the user subscriptions:
    $user_id = get_current_user_id();
    
    // Loop through user subscriptions
    foreach ( wcs_get_users_subscriptions($user_id) as $subscription ) {
        $end_date = $subscription->get_date('end');
    
        if (  ! empty($end_date) ) {
            echo '<p>End date: ' . $end_date . '</p>';
        }
    }
    
    1. You can use current() or reset() functions to get the subscription object, for only one subscription:
    $user_id = get_current_user_id();
    
    // Get the subscription object (for a unique subscription)
    $subscription = current( wcs_get_users_subscriptions($user_id) );
    
    $end_date = $subscription->get_date('end');
    
    if (  ! empty($end_date) ) {
        echo '<p>End date: ' . $end_date . '</p>';
    }