Last active
December 30, 2021 18:22
-
-
Save omniacode/8b7b061678ce7c5ffe1317e99c7b6e2f to your computer and use it in GitHub Desktop.
Change User Role Upon Product 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
<?php | |
// Single Product - Only Use One Snippet or the Other!! | |
function woo_change_role_after_purchase( $order_id ) { | |
// Get order object and items | |
$order = new WC_Order( $order_id ); | |
$items = $order->get_items(); | |
$product_id = 10; // Change 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( 'editor' ); | |
} | |
} | |
} | |
add_action( 'woocommerce_order_status_completed', 'woo_change_role_after_purchase' ); | |
// Multiple Products - Only Use One Snippet or the Other!! | |
function woo_change_role_after_purchase( $order_id ) { | |
// Get order object and items | |
$order = wc_get_order( $order_id ); | |
$items = $order->get_items(); | |
$products_to_check = array( '20', '21' ); // Add Product IDs Here | |
foreach ( $items as $item ) { | |
if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) { | |
$user = new WP_User( $order->user_id ); | |
// Remove old Role | |
$user->remove_role( 'customer' ); | |
// Add new Role | |
$user->add_role( 'editor' ); | |
// Exit the loop | |
break; | |
} | |
} | |
} | |
add_action( 'woocommerce_order_status_completed', 'woo_change_role_after_purchase' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment