questions

Automatically changing user role upon purchase in WooCommerce

Rate this post

I would like to make a members only section for WooCommerce customers who have made completed purchases, by assigning them a new role as the default for all registered users are “customer”.

I’ve stumbled across some code which can solve this, however with over 200 products in store, it would be a hassle to list all the products individually.

Is there anyway to give a customer who makes ANY purchase a new role?

This is the original code:

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' );
        }
    }
}

 

✔️Solution:

You can use the following instead, which will change the user role when a customer make a successful purchase (paid order):

add_action( 'woocommerce_order_status_processing', 'change_role_on_purchase', 10, 2 );
add_action( 'woocommerce_order_status_completed', 'change_role_on_purchase', 10, 2 );
function change_role_on_purchase( $order_id, $order ) {
    $user = $order->get_user(); // Get the WP_User Object

    // Check for "customer" user roles only
    if( is_a( $user, 'WP_User' ) && in_array( 'customer', (array) $user->roles ) ) {
        // Remove WooCommerce "customer" role
        $user->remove_role( 'customer' ); 

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

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Note: The WC_Order Object Is already an existing argument for that hooked function (missing from your code).


Addition: To remove all previous roles and assign a new role

This is possible using just the WP_User set_role() method, so in the code, replace:

// Remove WooCommerce "customer" role
$user->remove_role( 'customer' ); 

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

by:

// Reset user roles and set a new one
$user->set_role( 'editor' );

Leave a Reply

Your email address will not be published.

Back to top button