Skip to content

Instantly share code, notes, and snippets.

@nfsarmento
Created March 29, 2023 14:34
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 nfsarmento/5b1d9a5b62f8bdd33534665f8a14a4ee to your computer and use it in GitHub Desktop.
Save nfsarmento/5b1d9a5b62f8bdd33534665f8a14a4ee to your computer and use it in GitHub Desktop.
Add new role for specific product when order is completed WooCommerce
<?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