I am using the code below. I want to add an extra user role instead of the default 'customer' role right after an order is placed by a customer.
Unfortunately, the user role is not added by this code after an order is placed. Where did I miss?
add_action( 'woocommerce_order_status_completed', 'change_role_on_purchase' );
function change_role_on_purchase( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
$product_id = 73; // that's my product ID
foreach ( $items as $item ) {
if( $product_id == $item['product_id'] && $order->user_id ) {
$user = new WP_User( $order->user_id );
// Remove role
$user->remove_role( 'customer' );
// Add role
$user->add_role( 'premium' );
}
}
}