Reputation: 495
Is there any already-programmed method to get the last correctly-paid order for a given subscription?
$subscription->get_last_order()
will return the last associated order, no matter if that order involved a correct-payment or not.
$subscription->get_related_orders()
will return the whole list of orders, and the list can include pending-payment or failed orders.
Upvotes: 2
Views: 1383
Reputation: 311
I think if you wrap / trigger $subscription->get_last_order()
with the woocommerce_subscription_payment_complete
action (https://docs.woocommerce.com/document/subscriptions/develop/action-reference/) you would essentially achieve that objective. That hook fires both for initial subscription orders and renewal orders and will ensure the $last_order is paid for. Something like this:
add_action( 'woocommerce_subscription_payment_complete', 'set_last_order' );
function set_last_order( $subscription ) {
$last_order = $subscription->get_last_order( 'all', 'any' );
// If you want to be able to reference that $last_order at any time
// then you could just save/update that order ID to post meta so
// that you can grab it any time outside of the action.
}
}
I know that seems a little clunky, but it's the best way I can think of. The only other option that comes to mind would be to loop through $subscription->get_related_orders()
checking is_paid() from high IDs to low IDs and grabbing the first one from there.
Upvotes: 2