Set User Role Based On WooCommerce Product Purchase

Recommendation

Learn why I switched to WPCodeBox for managing code snippets for myself and for my clients.

Instructions

Snippet Type: PHP

  1. Copy the snippet.
  2. Add the snippet using WPCodeBox.
  3. Follow any customization notes provided.
  4. Save the snippet.
  5. Enable the snippet.
  6. Test.

Snippet

When You Only Need to Target One Product

Customization Notes

In the example here, when someone purchases the product that has a Product ID of 999, we are removing their old role (customer) and setting their new role to the ‘Premium Member’ premium_member) role.

You can get your Product ID, but pulling up your product list in the WordPress Dashboard and hovering over the product name.

  1. Adjust ‘$product_id = 999’, to reflect your particular Product ID.
  2. Adjust the ‘remove_role’ and ‘add_role’ entries as desired.
				
					// Set User Role Based On WooCommerce Product Purchases
add_action( 'woocommerce_order_status_completed', 'wptu_change_role_on_purchase' );

function wptu_change_role_on_purchase( $order_id ) {

// get order object and items
	$order = new WC_Order( $order_id );
	$items = $order->get_items();

	$product_id = 999; // that's a specific product ID

	foreach ( $items as $item ) {

		if( $product_id == $item['product_id'] && $order->user_id ) {
			$user = new WP_User( $order->user_id );

			// Remove old role
            $user->remove_role( 'customer' ); 

            // Add new role
            $user->add_role( 'premium_member' );
		}
	}
}
				
			

When You Need to Target Multiple Products

In the example here, when someone purchases any of the products that match Product ID of 268, 269, or 270,  we are removing their old role (‘subscriber’) and setting their new role to ‘customer’.

You can get your Product ID, but pulling up your product list in the WordPress Dashboard and hovering over the product name.

  1. Adjust ‘$products_to_check = array’, to reflect your particular Product IDs.
  2. Adjust the ‘remove_role’ and ‘add_role’ entries as desired.
				
					// Set User Role Based On WooCommerce Product Purchases
add_action( 'woocommerce_order_status_completed', 'wptu_change_role_on_purchase' );

function wptu_change_role_on_purchase( $order_id ) {

// get order object and items
    $order = wc_get_order( $order_id );
    $items = $order->get_items();

    $products_to_check = array( '268', '269', '270' );

    foreach ( $items as $item ) {
        if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) {
            $user = new WP_User( $order->user_id );

            // Remove role
            $user->remove_role( 'subscriber' ); 

            // Add role
            $user->add_role( 'customer' );

            // Exit the loop
            break;
        }
    }
}