85

How to Change User Roles in WooCommerce After Product Purchase

Powered by WPCodeBox

Learn how to automatically change user roles in WooCommerce after a product purchase. This snippet allows you to set new roles for customers based on their specific product purchases.


/**
 * Author: WP Turned UP
 * Author URI: https://wpturnedup.com
 */


//// In our 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.

 

----------------- CODE SNIPPET IS BELOW THIS LINE - REMOVE THIS LINE AND ABOVE ----------------- 

// Set User Role Based On WooCommerce Product Purchase
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' );
		}
	}
}

Other Snippets

WPCodeBox is a WordPress Code Snippets Manager that allows you to share your WordPress Code Snippets across your sites.