Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yuriinalivaiko/1bd14f3e4382741290ed8c183388d37f to your computer and use it in GitHub Desktop.
Save yuriinalivaiko/1bd14f3e4382741290ed8c183388d37f to your computer and use it in GitHub Desktop.
This code removes all old user roles if a new user role is assigned when subscription status is changed.
<?php
// Remove all old roles on subscription status change.
function um_woocommerce_subscription_status_changed_remove_old_roles( $subscription_id, $old_status, $new_status ) {
global $wpdb;
if ( ! UM()->WooCommerce_API()->api()->is_wc_subscription_plugin_active() ) {
return;
}
$subscription = wcs_get_subscription( $subscription_id );
$userdata = $subscription->get_user();
if ( empty( $userdata ) || is_wp_error( $userdata ) || UM()->WooCommerce_API()->api()->maybe_skip_user_by_role( $userdata->ID ) ) {
return;
}
$arr = array(
'active' => '_um_woo_product_activated_role',
'pending' => '_um_woo_product_downgrade_pending_role',
'on-hold' => '_um_woo_product_downgrade_onhold_role',
'expired' => '_um_woo_product_downgrade_expired_role',
'cancelled' => '_um_woo_product_downgrade_cancelled_role',
'pending-cancel' => '_um_woo_product_downgrade_pendingcancel_role',
);
$items = $subscription->get_items();
foreach ( $items as $item ) {
if ( empty( $arr[$new_status] ) ) {
continue;
}
$new_single_role_query = $wpdb->prepare(
"SELECT meta_value
FROM {$wpdb->usermeta}
WHERE user_id = %d
AND meta_key = %s",
$userdata->ID,
'_um_woo_subscription_' . $subscription_id . '_product_' . $item->get_product_id() . '_' . $new_status . '_role'
);
$new_single_role = $wpdb->get_var( $new_single_role_query );
if ( empty( $new_single_role ) || 'ignore' === $new_single_role ) {
continue;
}
if ( ! in_array( $new_single_role, $userdata->roles, true ) ) {
$userdata->add_role( $new_single_role );
}
foreach ( $userdata->roles as $role ) {
if ( $new_single_role !== $role ) {
$userdata->remove_role( $role );
}
}
}
UM()->user()->remove_cache( $userdata->ID );
}
add_action( 'woocommerce_subscription_status_changed', 'um_woocommerce_subscription_status_changed_remove_old_roles', 20, 3 );
@yuriinalivaiko
Copy link
Author

This code is a patch that changes the roles assignment logic for subscriptions in the extension Ultimate Member - WooCommerce. This code removes all old user roles if a new user role is assigned when subscription status is changed.

Add this code to the file functions.php in the active theme directory to use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment