4
25/11/2024 12:53 pm
Emne starter
Is it possible to change a user's role after they purchase from a specific WooCommerce product category using a code snippet in the functions.php file?
Thanks!
2 Svar
3
25/11/2024 12:55 pm
Use this code:
function change_user_role_after_category_purchase($order_id) {
// Get the order object
$order = wc_get_order($order_id);
// Get the user ID of the customer
$user_id = $order->get_user_id();
// Define the target product category
$target_category = 'example-category'; // Replace with your category slug
// Check if the order contains products from the target category
foreach ($order->get_items() as $item_id => $item) {
$product_id = $item->get_product_id();
if (has_term($target_category, 'product_cat', $product_id)) {
// Change the user role
$user = new WP_User($user_id);
$user->set_role('new_role'); // Replace 'new_role' with your desired role slug
// Exit the loop after finding a match
break;
}
}
}
add_action('woocommerce_order_status_completed', 'change_user_role_after_category_purchase');
-
Replace the placeholders:
- Replace
example-categorywith the slug of your target product category. - Replace
new_rolewith the role you want to assign (e.g.,subscriber,customer,editor, etc.).
- Replace
-
Add the code:
- Navigate to your WordPress Dashboard.
- Go to
Appearance > Theme File Editor. - Open the
functions.phpfile of your active theme and paste the code at the bottom.
-
Test the functionality:
- Make a test purchase from the target category and ensure the user role is updated after the purchase is marked as "Completed."
2
25/11/2024 12:57 pm
You can also use the plugin Automatic User Roles Switcher for WooCommerce (although I had a conflict with it):
https://woocommerce.com/products/automatic-user-roles-switcher/
