How to get the Product ID from a WC_Subscription instance Object

心已入冬 提交于 2020-07-23 05:45:19

问题


This one for completed initial subscription payments and subscription renewals.

function payment_made($subscription){
    // How do I get the Product ID from subscription? (Definitely need this)
}
add_action("woocommerce_subscription_payment_complete", "payment_made");

And this one for when a status is changed, so I can handle manual and system changes either manual overrides or failed/pending/active/whatever status based of payments or switches.

function status_update($subscription, $old_status, $new_status){
    // How do I get the Product ID from subscription (Definitely need this)
}
add_action("woocommerce_subscription_status_updated", "status_updated");

回答1:


To get the product id from the WC_Subscription Object, you will need to loop through order items (as you can have many) using the method get_items() like:

$order_items = $subscription->get_items();

// Loop through order items
foreach ( $order_items as $item_id => $item ) {
    // Get the WC_Product_Subscription Object
    $product = $item->get_product();

    // Get the Product ID
    $product = $product->get_id();

    // For subscriptions variations, to get the variable product ID
    $product = $item->get_product_id();
}

Tested and works.



来源:https://stackoverflow.com/questions/63043386/how-to-get-the-product-id-from-a-wc-subscription-instance-object

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