How to get products associated with a subscription in WooCommerce

caleb woods 1132368 unsplash

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:

/**
* 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.

Leave a Reply

Your email address will not be published. All fields are required.