Assign a User Role per specific products.

Assign a User Role per specific products.

Working on an e-commerce site, I realized that customers purchasing a certain product needed to assign a specific role in addition to the default “customer” role assigned by Woocommerce. This is the way to do it.
In your unctions.php add the following snippet:
<?php
/**
 * Assign a specific User Role after purchasing specific products.
 * Modify the $product_id_roles array with the actual product IDs and roles.
 */
function assign_role_after_product_purchase( $order_id ) {
    // 1. Define roles based on the product
    // The key is the WooCommerce Product ID, the value is the User Role name
    $product_id_roles = array(
        '1' => 'roleA', // Example: Product ID 1 assigns Role 'roleA'
        '2' => 'roleB', // Example: Product ID 2 assigns Role 'roleB'
        '3' => 'roleC', // Example: Product ID 3 assigns Role 'roleC'
        // Add the other courses here...
    );

    $order = wc_get_order( $order_id );
    $user = $order->get_user();

    // I verify that the order is completed and that it is a registered user
    if ( ! $order->is_paid() || ! $user || ! is_a( $user, 'WP_User' ) ) {
        return;
    }

    $assigned_roles = array();

    // I scroll through the order items to see if one of the involved products
    foreach ( $order->get_items() as $item ) {
        $product_id = $item->get_product_id();
        
        if ( array_key_exists( $product_id, $product_id_roles ) ) {
            // I get the role to assign for this specific product
            $assigned_roles[] = $product_id_roles[ $product_id ];
        }
    }

    // If one or more courses were found in the order
    if ( ! empty( $assigned_roles ) ) {
        
        // I assign roles (if there are more than one) to the user
        foreach ( array_unique( $assigned_roles ) as $role_to_be_assigned ) {
            $user->add_role( $role_to_be_assigned );
        }
    }
}
add_action( 'woocommerce_order_status_completed', 'assign_role_after_product_purchase', 10, 1 );

Be the Lord of Online Commerce 🤴💳

Do you want more tips?