1

我目前正在开发一个 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
) );

当用户购买订阅时,用户可以选择订阅数量。所以我需要得到这个字段的值:

在此处输入图像描述

4

2 回答 2

1

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

测试和工作。

于 2020-02-17T14:56:58.623 回答
0

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

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

谢谢

于 2020-02-17T12:52:32.763 回答