yanike
yanike

Reputation: 847

How to get the Product ID from a WC_Subscription instance Object

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

Upvotes: 2

Views: 2355

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253901

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();

    // To get the subscription variable product ID and simple subscription  product ID
    $product_id = $item->get_product_id();

    // To get the variation subscription product ID
    $variation_id = $item->get_variation_id();

    // Or to get the simple subscription or the variation subscription product ID
    $_product_id = $product->get_id();
}

Tested and works.

Related:

Upvotes: 7

Related Questions