I have a Woocommerce store with a variable subscription and 3 types of subscription variations: subscription-a, subscription-b and subscription-c. I also added 3 new types of user roles: subscriber-a, subscriber-b and subscriber-c.
I’m trying to create a function that when a customer purchase, upgrade or downgrade a subscription and the subscription is active, the parallel user role will be assign to this customer.
For example:
If a costumer purchase subscription-a, the user role subscriber-a a will be assigned once active.
If a costumer upgrade from subscription-b to subscription-c, the user role will chance from subscriber-b to subscriber-c once active.
I tried the function offered in a similar thread but it didn’t work for me: Woocommerce change user role on purchase
function change_role_on_purchase( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
if ( $order->user_id > 0 && $product_variation_id == '416' ) {
update_user_meta( $order->user_id, 'paying_customer', 1 );
$user = new WP_User( $order->user_id );
// Remove role
$user->remove_role( 'subscriber' );
// Add role
$user->add_role( 'subscriber-a' );
}
}
}
add_action( 'woocommerce_subscription_status_active', 'change_role_on_purchase' );
Update:
The solution of @LoicTheAztec works great. I am now trying to remove roles when the subscription is cancelled. This is what I got, not sure if this is the most elegant way to do it but it works.
add_action('woocommerce_subscription_status_cancelled', 'cancelled_subscription_remove_role', 10, 1);
function cancelled_subscription_remove_role($subscription) {
$user_id = $subscription->get_user_id();
$user = new WP_User($user_id);
$user->remove_role('subscriber_a');
$user->remove_role('subscriber_b');
$user->remove_role('subscriber_c');
}
2
Answers
Updated to handle switched subscriptions too (upgrade or downgrade a subscription)
You can try to use use
woocommerce_subscription_status_updated
related hook.In the code below, you will set for each variation ID, the related user role in the settings array (commented code):Code goes in functions.php file of your active child theme (or active theme). It could works.
Or you can also try with
woocommerce_subscription_status_active
hook:Code goes in functions.php file of your active child theme (or active theme). It should works.
Documentation: Subscriptions Action Hook Reference
Bit updated code from LoicTheAztec. Made to work with different products in subscription.