Created
December 30, 2018 20:39
-
-
Save wjlevay/d7f898300acdc50cf46a422f51ac2c47 to your computer and use it in GitHub Desktop.
Change user role after purchase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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