While selling online products, you might be offering different plans to attract different types of customers. Based on the products that customers purchase, you may want to automatically assign a certain role to customers. For example, a fitness website selling a “Premium Fitness Membership” can automatically give customers access to special workout plans and diet guides as soon as they buy the membership product.
In this guide, we’ll show you how to change user roles after a customer purchases a product from a specific product category in woocommerce.
Solution: Change User Role After Purchasing Specific Product Category Products WooCommerce
The code will automatically change a user’s role to Premium Member in WooCommerce when users buy a product categorized under “premium-membership”.
Note: This code is designed to work with the ‘premium member’ user role. If you want to apply it to a different user role, you’ll need to update the role name accordingly.
add_action( 'woocommerce_thankyou', 'ts_change_user_role_for_premium_membership' ); function ts_change_user_role_for_premium_membership( $order_id ) { if ( ! $order_id ) return; $order = wc_get_order( $order_id ); $user_id = $order->get_user_id(); if ( ! $user_id ) return; // Ensure the user is logged in $user = new WP_User( $user_id ); // Category slug that triggers role change $premium_category = 'premium-membership'; $premium_role = 'premium_member'; foreach ( $order->get_items() as $item ) { $product_id = $item->get_product_id(); $product_categories = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'slugs' ) ); if ( in_array( $premium_category, $product_categories ) ) { $user->set_role( $premium_role ); // Assign only the premium role break; // Exit once a match is found } } }
Output
Let’s say the product Digital Magazine is categorized under Premium Subscription products. When a customer purchases this product, their user role will automatically change to Premium Membership, granting them immediate access to the product’s exclusive content.
Now that you’ve successfully assigned user roles based on purchases, you can take it a step further by restricting certain user roles from changing the WooCommerce order status. For example, you might want to stop store managers from editing completed orders and allow only administrators to make changes. This helps admins to have control over order management and ensures everything runs smoothly.