如何获取 WooCommerce 订阅的数量?

How to get quantity of a WooCommerce subscription?

我目前正在开发一个 WordPress 项目,我正在使用带有 WooCommerce 订阅插件的 WooCommerce 为我的用户提供订阅。我需要有关如何获取 PHP 中订阅数量的帮助。

我正在使用此代码进行订阅,但无法检索数量:

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

当用户购买订阅时,用户可以select订阅的数量。所以我需要获取这个字段的值:

这是我的工作代码试试这个

$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"
) );

谢谢

您的代码是正确的,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>';
            }
        }
    }
}

已测试并有效。