Как получить количество подписок WooCommerce?

В настоящее время я разрабатываю проект WordPress и использую WooCommerce с плагином WooCommerce Subscriptions, чтобы предлагать подписки своим пользователям. Мне нужна помощь в том, как получить количество подписки в PHP.

Я использую этот код для получения подписки, но не могу получить количество:

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

Когда пользователь покупает подписку, он может выбрать количество подписок. Итак, мне нужно получить значение этого поля:

введите здесь описание изображения


person Besart    schedule 17.02.2020    source источник


Ответы (2)


Ваш код правильный, и wcs_get_subscriptions() – это правильный и лучший способ получить активные подписки клиентов.

Но вы что-то пропустили после своего кода для получения количества товара по подписке клиента (код прокомментирован):

// Get current customer active subscriptions
$subscriptions = wcs_get_subscriptions( array(
    'customer_id'            => get_current_user_id(),
    'subscription_status'    => 'wc-active',
    'order_by'               => 'DESC',
    'subscriptions_per_page' => - 1
) );

if ( count( $subscriptions ) > 0 ) {
    // Loop through customer subscriptions
    foreach ( $subscriptions as $subscription ) {
        // Get the initial WC_Order object instance from the subscription
        $order = wc_get_order( $subscription->get_parent_id() );

        // Loop through order items
        foreach ( $order->get_items() as $item ) {
            $product = $item->get_product(); // Get the product object instance

            // Target only subscriptions products type
            if( in_array( $product->get_type(), ['subscription', 'subscription_variation'] ) ) {
                $quantity = $item->get_quantity(); // Get the quantity
                echo '<p>Quantity: ' . $quantity . '</p>';
            }
        }
    }
}

Проверено и работает.

person LoicTheAztec    schedule 17.02.2020

Вот мой рабочий код, попробуйте это

$current_user_id = get_current_user_id();
$customer_subscriptions = get_posts( array(
    'numberposts' => -1,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(), // Or $user_id
    'post_type'   => 'shop_subscription', // WC orders post type
    'post_status' => 'wc-active' // Only orders with status "completed"
) );

И если вы хотите получить всю подписку post_status, используйте это


$customer_subscriptions_for_other_cases = get_posts( array(
    'numberposts' => -1,
    'meta_key'    => '_customer_user',
    'meta_value'  => get_current_user_id(), // Or $user_id
    'post_type'   => 'shop_subscription', // WC orders post type
    'post_status' => array('wc-on-hold','wc-pending-cancel','wc-active') // Only orders with status "completed"
) );

Спасибо

person rajat.gite    schedule 17.02.2020
comment
@LoicTheAztec Это то, что мне нужно. - person Besart; 17.02.2020