OiO.lk English PHP Assign a Custom User Role Upon WooCommerce Subscription Activation
PHP

Assign a Custom User Role Upon WooCommerce Subscription Activation


I’m working on a WooCommerce site where I need to automatically assign a custom role ("Active Production Company") to users upon their subscription becoming active. The role assignment will allow only active subscribers to access and submit a restricted form on the site, created with WP Job Manager. I’ve added a WooCommerce subscription product (monthly and yearly) for users to purchase, which grants them the custom role upon successful payment.
Here’s the code I’m currently using:

`add_action( ‘woocommerce_subscription_status_updated’, ‘wc_subscribe_assign_role’, 10, 3 );

function wc_subscribe_assign_role( $subscription, $new_status, $old_status ) { if ( $new_status === ‘active’ ) {
$user_id = $subscription->get_user_id(); // Get the user ID of the subscriber $user = new WP_User( $user_id );

    // Assign the "Active Production Company" role upon subscription activation`
    $user->set_role( 'active_production_company' );`
}`

}`

I’m not certain if $subscription is being used correctly to get the user ID, or if woocommerce_subscription_status_updated is the best hook for this purpose.

I used the woocommerce_subscription_status_updated hook, hoping it would trigger role assignment upon a subscription’s status change to "active." I expected this to automatically assign the "Active Production Company" role to users, allowing them to access the restricted form.

After testing with a test order, the expected role was not applied. I checked the WooCommerce subscription object documentation and my error logs but couldn’t confirm if the $subscription->get_user_id() part was working as intended. I’d appreciate any insights or suggestions for achieving this functionality reliably!



You need to sign in to view this answers

Exit mobile version