Today i will show you how to add user to group after product purchase. The snippet presented, applies if you use Groups plugin from itthinx and WooCommerce plugin.
However, you can use the hook to apply whatever you want. There are several occasions where you want to do something, when an order is complete.
The use case is this. You want to add the new user/customer to a specific group, after buying a specific product. The steps below explain the logic of the snippet following.
First we disable guest checkout in WooCommerce.
We want to create a new user to the site, so we force customers to register. This option is under WooCommerce Settings, in Checkout tab.
Second, everything must happen after the purchase.
So, we need a hook to trigger after the purchase is made. In other words, after the order is complete. The suitable hook for the process is this. Another useful detail is that it triggers whether you use auto-complete or change the order status manually.
woocommerce_order_status_completed
Third, get the order data.
We need the order data to check if the desired product is involved. Also, we need to extract the user id from the order, in order to add him to the desired group.
Fourth, add user to group.
The process is simple. We get the user id and we add user to group with the create method of Groups_User_Group class like this. The API of Groups is availiable in the documentation page.
Groups_User_Group::create( array( 'user_id' => $my_user_id, 'group_id' => $group_id ) );
Finally, the code snippet.
Put this snippet in your child theme’s function.php file and let it do the job.
add_action( 'woocommerce_order_status_completed', 'gt_add_user_to_group' );
function gt_add_user_to_group( $order_id ) {
$order = new WC_Order( $order_id );
$my_user_id = $order->user_id;
$items = $order->get_items();
foreach ( $items as $item ) {
if ( $item->get_product_id() == 2399 ) {
if ( $group = Groups_Group::read_by_name( 'Premium' ) ) {
// Add user to group 'Premium'
Groups_User_Group::create( array( 'user_id' => $my_user_id, 'group_id'=>$group->group_id ) );
}
}
}
}
Try a test purchase and visit the Users page to see results.
What other applications can you think of when an order is complete? Share your ideas in the comments.

Leave a Reply