How to get products associated with a subscription in WooCommerce

This is the scenario: you’ve got a WooCommerce subscription and you’d like to find what products comprise the subscription. You can use the following piece of code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* How to get the product associated with a WooCommerce subscription | |
*/ | |
function ct_checkout_subscription_created( $subscription, $order, $recurring_cart ) { | |
$id = $subscription->get_id(); // You can use this to set meta in the subscription | |
// Get the products in the order | |
$items = $order->get_items(); | |
foreach( $items as $item ) { | |
$product = $item->get_product(); | |
$product_id = $product->get_id(); | |
// ... Do your stuff here | |
} | |
} | |
// Use any hook that passes the $subscription object | |
add_action( 'woocommerce_checkout_subscription_created', 'ct_checkout_subscription_created', 10, 3 ); |
If you need to, you can use a different hook – you just need one that will pass the subscription object or ID.