Woocommerce Subscriptions: Determine if a User Is Switching Their Existing Subscription, or Creating a Brand New One
This took me some digging to sort out, but say you want to determine, on the order-received endpoint in Woocommerce, if the customer has just purchased a new subscription, or if they’re just switching an existing one.
Note: the order-received endpoint is just a fancy way of saying they’re on the order confirmation screen, which usually has a URL like https://yourawesomewebsite.com/checkout/order-received/
First, create a function to determine if the order is a switch-order.
// determine if the order is a switch-order or first time subscription
function ws_is_switch_order( $order_id ) {
$order = wc_get_order( $order_id );
if ( wcs_order_contains_subscription( $order, 'switch' ) ) {
return true; // This is a switch order
} else {
return false; // This is a new subscription order
}
}
Then use it something like so, when you’re on the order-received endpoint
// Get the order key from the query string
$order_key = isset( $_GET['key'] ) ? sanitize_text_field( $_GET['key'] ) : '';
// Get the order ID from the order key
$order_id = wc_get_order_id_by_order_key( $order_key );
// Get the WC_Order object
$order = wc_get_order( $order_id );
// You can also get the order ID directly from the $order object
$order_id = $order->get_id();
if ( wc_is_switch_order($order_id) ) {
// this should only occur when switching subscriptions
// do something when they switch their subscription
} else {
// this should be what happens when creating a new subscription
// do something when they are buying a new order
}
Up Next: How to Remove the Default Classes and ID From Wp Nav Menus, but Keep Your Custom Classes