WooCommerce Subscriptions - Get product of a specific subscription

ⅰ亾dé卋堺 提交于 2019-12-12 20:42:42

问题


Is there a way to get from $product from $subscription?

Thanks to this post, I know that from $subscription I can get $order:

$order = $subscription->order;

Is this also possible?

$product = $subscription->product;

Or:

$product = $order->product;

回答1:


It is possible to get the products from either the Subscription or the matching order, as a subscription object is an extension of the WC_Order class.

$subscription_products = $subscription->get_items();
$order_products = $subscription->order->get_items();

In most situations where you provide subscription services, both of these will be equivalent or $order_products should at least contain all products found within $subscription_products.

A notable exception is when you create a subscription manually; no order will be attached to the subscription, so $subscription->order may not be a valid WC_Order object.




回答2:


Get product from woocommerce subscription full code with examples of use:

if ( sizeof( $subscription_items = $subscription->get_items() ) > 0 ) {
    foreach ( $subscription_items as $item_id => $item ) {
        $product = $item->get_product();

        //Examples of use
        $product->get_id();
        $product->get_sku();
        $product->get_image('post-thumbnail', ['class' => 'alignleft'], false); // main image

        $product_id = wcs_get_canonical_product_id( $item ); // get product id directly from item
    }
}



回答3:


Yes, if you have a "subscription ID" you can get an object like this:

$subscription = new WC_Subscription( $the_id );

When you already have $subscription object:

$related_orders_ids_array = $subscription->get_related_orders();

Then loop through array of related orders.

foreach ( $related_orders_ids_array as $order_id ) {

    $order = new WC_Order( $order_id );
    $items = $order->get_items();

then if you loop through order items, you can access product information:

    foreach ( $items as $product ) {

        var_dump( $product );

    }

}


来源:https://stackoverflow.com/questions/44829634/woocommerce-subscriptions-get-product-of-a-specific-subscription

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!