Skip to content

Instantly share code, notes, and snippets.

@jrick1229
Last active February 15, 2019 15:58
Show Gist options
  • Save jrick1229/3885c111cb0625b84570b73f9b9c2414 to your computer and use it in GitHub Desktop.
Save jrick1229/3885c111cb0625b84570b73f9b9c2414 to your computer and use it in GitHub Desktop.
Assign a new specified role based on the products that are purchased in the order.
<?php
function adding_new_role_for_product_purchase() {
//add the test-1 customer role
add_role(
'test-1',
"TEST 1 ROLE",
array(
'read' => true,
'delete_posts' => false
)
);
//add the test-2 customer role
add_role(
'test-2',
"TEST 2 ROLE",
array(
'read' => true,
'delete_posts' => false
)
);
}
add_action('admin_init', 'adding_new_role_for_product_purchase');
add_action( 'woocommerce_thankyou', 'update_user_role_upon_purchase_of_specified_product_IDs' );
function update_user_role_upon_purchase_of_specified_product_IDs( $order_id ) {
//access the order to retrieve product's purchased
$order = wc_get_order( $order_id );
$items = $order->get_items();
//define the products that should be checked for
$products_1 = array( '920', '664' );
$products_2 = array( '759', '663' );
foreach ( $items as $item ) {
//change user role based on $products_1 array
if ( $order->user_id > 0 && in_array( $item['product_id'], $products_1 ) ) {
$user = new WP_User( $order->user_id );
// Change role
$user->remove_role( 'subscriber' );
$user->remove_role( 'customer' );
$user->add_role( 'test-1' );
// Exit the loop
break;
}
//change user role based on $products_2 array
if ( $order->user_id > 0 && in_array( $item['product_id'], $products_2 ) ) {
$user = new WP_User( $order->user_id );
// Change role
$user->remove_role( 'subscriber' );
$user->remove_role( 'customer' );
$user->add_role( 'test-2' );
// Exit the loop
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment