Change User Role After Purchasing Product

Want to change user role after purchase Automatically in WooCommerce?

  1. Change user rule
  2. For multiple products
  3. Automatically complete orders
  4. Find product ID

If you restrict Content, Products, or other services on your site to a certain membership level, Users have to purchase a certain product or Membership plan from your WooCommerce Powered store to access it.

And,

You want to automate the process of changing the User Role When an order is completed with product id from ‘customer’ to ‘editor’ or any other membership level.

Too Easy… Just add the below code snippets in your theme’s functions.php file. ( Recommend to use Child Theme) and follow the instructions written below the snippet.

Code Snippet to change user role after purchase

add_action( 'woocommerce_order_status_completed', 'wpglorify_change_role_on_purchase' );

function wpglorify_change_role_on_purchase( $order_id ) {

// get order object and items
	$order = new WC_Order( $order_id );
	$items = $order->get_items();

	$product_id = 56; // 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 old role
            $user->remove_role( 'customer' ); 

            // Add new role
            $user->add_role( 'editor' );
		}
	}
}

Instructions:

In the above code snippet, number ( 56 ) in code on line  is the products’ ID to check. This means that snippet will check if that product purchased by the customer is in that list.

If yes, the user role will change to what you define on line 17. In this example ( ‘customer’ ) to ( ‘editor’ ) the role, we defined in line number 20 which is ‘editor’.

For multiple products

The above code snippet only works for one product. If you have multiple products where you want to change the user rule after purchase, kindly use this snippet.

It’s pretty much same except with multiple product id as an array.

add_action( 'woocommerce_order_status_completed', 'wpglorify_change_role_on_purchase' );

function wpglorify_change_role_on_purchase( $order_id ) {

// get order object and items
    $order = wc_get_order( $order_id );
    $items = $order->get_items();

    $products_to_check = array( '229', '6934' );

    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 role
            $user->remove_role( 'customer' ); 

            // Add role
            $user->add_role( 'editor' );

            // Exit the loop
            break;
        }
    }
}

You can change the product ID on line 9 where it mentioned $products_to_check = array( '229', '6934' ).

Number 229 and 6934 is the ID of the products to check. You need to change that pointing to your products

Automatically Complete Orders

This code works, but there is one catch, You have to mark order completed manually as it’s the default behavior of WooCommerce.

Good News is you can automate this order completion as well.

All you have to is add the following code snippets in your finctions.php file, just like the previous snippet.

/**
 * Auto Complete all WooCommerce orders.
 */
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );
function custom_woocommerce_auto_complete_order( $order_id ) { 
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );
    $order->update_status( 'completed' );
}

How to find post or product ID

This video will show you how to find a product Id. The video itself is about WordPress categories, but the process is the same for Products as well.

Basically, you just hover on any product in the WordPress dashboard and you will see the product ID under the title of the products.

Where to add this code?

You can place PHP snippets at the bottom of your functions.php file; We recommend to use a child theme so you will not lose any changes when updating your theme –.

Did this snippet work?

Please let us know in the comments if the snippet worked as expected. We would be happy to revise the code if you report otherwise or in case you need more assistance.

Managing Memberships

Now you have the ability to change membership levels automatically but are you struggling to manage all the memberships. Why not make things easy?

WooCommerce Memberships works out of the box it’s not only restricting your site’s content: it’s a simple, site-wide membership solution that brings your content, shop, and memberships together.

You can use this in addition to the above code snippet to change membership levels automatically.

Watch the video below to understand the Power WooCommerce Membership Plugin

Some of the main Features (but not limited).

  • Membership plans are created independently from products.
  • Grant access to the same membership from several products (i.e., a yearly purchase or a monthly subscription)
  • It lets you schedule when your members should have access to content. For example, you can require that customers be a member for 2 days before accessing certain posts or pages.
  • Can determine which content is included in a free trial period.
  • Allow you to create members-only products.
  • Add your own notes for your reference for any Member for easy communication.
  • Expiration and renewal reminder emails

30 Comments

      • Hi Gary, I’m wondering if you can help me as the code isn’t working for me also. I tried to check your test site but it says the server is down. I am copying and pasting the code exactly as you have done.

        The automatic order completion works.

        However, the coding above doesn’t work, when someone purchases something by default their role is set to “Customer” by woocommerce. I would like this changed to Editor.

        However, I have added the code for the specific product and it still doesn’t work 🙁

        The code is below

        [code removed]

        • Hi Ali, I just checked the code and it works with the latest version of woocommerce. Just make sure to replace product ID in the code with correct product ID.

          • Hi Ezekiel, you see code on line 9

            $product_id = 56;

            If you need to add more than ID you can write like this

            $product_id = 56, 90, 20;

            where 90 and 20 is the product ID’s

          • Sorry Neil, ? I should have tested the code first. I updated the article with instructions on how to add multiple products.

          • Hi,
            When I enter product ID 21265; it works.

            But when I try to put more than one product ID 21265, 21326, 47845, 54698, 54701, 66464, 66471; on line 9 displays this error ( syntax error, unexpected ‘,’ )

            How do I do that?

          • Complementing:

            In my case, any product ID other than 6075, 6128, 6129, 5984, 6131, 6132 should change to ‘customer-x’

            Because the WooCommerce Subscription plugin changes the function to ‘subscriber’ when one of these IDs is purchased.

            So I want to change the others that are not subscriptions (magazine or course) for example to customer-1.

            ***********************************************************
            Woo Commerce Subscription >> subscriber (ok)
            WordPress create an account >> customer-y (ok)
            Any other product ID different >> customer-x (non ok)
            ***********************************************************

            Can you help me?

  1. This is not working for me but it is exactly what I need. Please contact me with any assistance you can provide. Thank You!


    get('Version')
    );
    }
    add_action( 'wp_enqueue_scripts', 'child_theme_enqueue_styles' );

    add_action( 'woocommerce_order_status_completed', 'change_role_on_purchase' );
    function change_role_on_purchase( $order_id ) {
    $order = wc_get_order( $order_id );
    $items = $order->get_items();

    $products_to_check = array( '178' );

    foreach ( $items as $item ) {
    if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) {
    $user = new WP_User( $order->user_id );

    // Change role
    $user->remove_role( 'customer' );
    $user->add_role( 'shopper' );

    // Exit the loop
    break;
    }
    }
    }
    ?>

  2. Great snippet. thanks for sharing. However, could you help me out if we want to check only from a particular product category and not specific product ID.

    Please share the entire snippet.

  3. Thank for this snippet.

    In the event that you do not know the current role of the user, simply make the following changes:

    Remove line 17 completely……. $user->remove_role( ‘subscriber’ );

    Change line 20 from:
    $user->add_role( ‘editor’ );

    to:

    $user->set_role( ‘editor’ );

    ‘set_role’ will remove the previous roles of the user (whatever it is) and assign the new role.

    • Thanks for your input @osobase. The reason I choose ‘add_role’ instead ‘set_role’ just in case someone using more than one type of user role.

  4. Thank you.
    How do you change this code so that it automatically changes role if any order is made (not specific product)

  5. Hi,

    any idea of how to change the role back to trhe beginning when the member cancels subscription?

    Thanks, Bernd

  6. How do i do this using a custom plugin? Is there any way to not use it on theme’s functions.php and make a custom plugin for this snippet?

  7. Hi thanks for the great article, instead of changing, do you know how to add an existing role to a user? eg woocomerce customer role adds another user role when an item or multiple items are purchased and vice versa when a client makes an appointmentment they will receive a woocommerce customer role. Eg mulitple user roles per user upon purchasing and creating an appointment.

  8. Hello,
    thanks for the helpful snippet!
    Is it possible to easily give different products different user roles without a membership plugin?

    thanks for help

  9. hello, thanks for the class snippet! is it possible to assign between 3-5 products to different user roles?

    as an example
    product 51=customer
    product 62=admin
    etc.

    thanks for the answer and the help

    greet JJ

  10. Hello

    Thanks! Great Solution 🙂 But i need another solution:

    Product ID: 4186 -> Role “customer” to “seller” – Works fine !

    and i need another Role for another Product..

    Product ID: 4222 -> Role “customer” to “vendor”

    How can i make the code for 2 Product with different Role

    • To make it work for two products, you can duplicate the code in two places for two products and change only the function name: “wpglorify_change_role_on_purchase()” to anything in the other code so you don’t have duplicate function trying to run two different codes based upon two different conditions

  11. Thank you so much, GREAT GREAT article. One thing I did, changed “woocommerce_order_status_completed” to “woocommerce_order_status_processed” so avoided all products to be converted to completed!

  12. Hello Garry Singh,
    This is very useful, but wondering if you can customize it a little bit further, the plan is to have a one-month subscription and one year, so how will the countdown work? This is to change the user role back to Customer/subscriber after that particular time?

Leave a Reply

Your email address will not be published. Required fields are marked *