Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save daddiofaddio/1d06dd3359a78e40ab4bba39f14c218d to your computer and use it in GitHub Desktop.
Save daddiofaddio/1d06dd3359a78e40ab4bba39f14c218d to your computer and use it in GitHub Desktop.
Woocommerce add user role at time of purchase based on product ID
/* ADD USER ROLE BASED ON PRODUCT ID */
function change_role_on_purchase($order_id) {
$order = new WC_Order($order_id);
$items = $order->get_items();
foreach ($items as $item) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
if ($order->user_id > 0 && $product_id == '62') {
update_user_meta($order->user_id, 'subscriber', 1);
$user = new WP_User($order->user_id);
// Remove role
$user->remove_role('subscriber');
// Add role
$user->add_role('subscriber');
$user->add_role('silver');
}
}
}
add_action('woocommerce_order_status_completed', 'change_role_on_purchase');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment