I'm trying to assign user roles based on a few different criteria:
- If a user purchases Item-A, user-role-a is assigned.
- If a user purchases Item-B, user-role-b is assigned.
- If a user purchases 2 or more of Item-B, user-role-c is also assigned.
So multiple user roles can be assigned. Based on Change User Role After Purchasing Product, this is my attempt:
add_action( 'woocommerce_order_status_completed', 'wpglorify_change_role_on_purchase' );
function wpglorify_change_role_on_purchase( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
// CHILD PRODUCT MAKES PRIMARY ADULT ROLE
$product_id = 50; // that's the child product ID
foreach ( $items as $item ) {
if( $product_id == $item['product_id'] && $order->user_id ) {
$user = new WP_User( $order->user_id );
// Add new role
$user->add_role( 'primary-adult' );
}
}
// ADULT PRODUCT MAKES ADULT ROLE
$product_id = 43; // that's the adult product ID
foreach ( $items as $item ) {
if( $product_id == $item['product_id'] && $order->user_id ) {
$user = new WP_User( $order->user_id );
// Add new role
$user->add_role( 'adult' );
}
}
}
With my code I was able to get a bit of a solution (assign roles based on purchased product IDs), but I still need to be able to assign a role based on the quantity of a purchased item. Any advice?