简体   繁体   中英

Automatically changing user role upon purchase in WooCommerce

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

Updated

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM