Skip to content

Instantly share code, notes, and snippets.

@wjlevay
Created December 30, 2018 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wjlevay/d7f898300acdc50cf46a422f51ac2c47 to your computer and use it in GitHub Desktop.
Save wjlevay/d7f898300acdc50cf46a422f51ac2c47 to your computer and use it in GitHub Desktop.
Change user role after purchase
// If customer purchases a special product, change user role to allow access to that product
// Make sure to add corresponding value to product's custom field "new_role"
add_action( 'woocommerce_order_status_completed', 'change_role_on_purchase' );
function change_role_on_purchase( $order_id ) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item->get_product_id();
$new_role = get_post_meta( $product_id, 'new_role', true );
if ( $order->user_id > 0 && (!empty($new_role)) ) {
$user = new WP_User( $order->user_id );
// Change role
$user->remove_role( 'customer' );
$user->add_role( $new_role );
// Exit the loop
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment