Created
March 29, 2023 14:34
-
-
Save nfsarmento/5b1d9a5b62f8bdd33534665f8a14a4ee to your computer and use it in GitHub Desktop.
Add new role for specific product when order is completed WooCommerce
This file contains hidden or 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 | |
/* | |
* | |
* Add new role for specific product when order is completed WooCommerce | |
* | |
* */ | |
add_action( 'woocommerce_order_status_completed', 'ns_change_role_on_purchase' ); | |
function ns_change_role_on_purchase( $order_id ) { | |
// get order object and items | |
$order = new WC_Order( $order_id ); | |
$items = $order->get_items(); | |
$product_id = 3439; // 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 role | |
$user->remove_role( 'customer' ); | |
// Add role | |
$user->add_role( 'subscriber' ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment