61

How to Set User Roles Based on WooCommerce Product Purchases

Powered by WPCodeBox

Learn how to set user roles in WooCommerce based on product purchases. Easily assign ‘Premium Member’ or other custom roles to customers after they buy a specific product by adjusting product ID and desired roles.


// Set User Role Based On WooCommerce Product Purchase
add_action( 'woocommerce_order_status_completed', 'wpglorify_change_role_on_purchase' );

function mlc_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.