简体   繁体   中英

Woocommerce default role and role after purchase

I found this thread but it doesn't exactly do what I'm looking for.

My question is, how can I change the default Woocommerce role "customer" to, eg "Subscriber" for new registered users. And then, if user checks out (purchases product), change the role from "Subscriber" to "Customer".

I'm asking this as I want to show different content per user roles: "registered customer" and "subscribed (paid) customer".

The first part of your question is changing the default role of user that is created by WooCommerce. Honestly, I'd probably leave the default role as customer. And then create a new role/capability for people who purchase your specific product.

add_filter( 'woocommerce_new_customer_data', 'so_29647785_default_role' );

function so_29647785_default_role( $data ){
    $data['role'] = 'subscriber'; // the new default role
    return $data;
}

As you saw in my other answer (well my re-posted answer), you can do things once the user has finished paying, but hooking into the woocommerce_order_status_completed hook.

To adapt that code to do something specific to a particular product, you need to loop through the order items and check them against a product ID. Replace 999 with the ID of the product in question.

add_action( 'woocommerce_order_status_completed', 'so_29647785_convert_customer_role' );

function so_29647785_convert_customer_role( $order_id ) {

    $order = new WC_Order( $order_id );

    if ( $order->user_id > 0 ) {

        foreach ( $order->get_items() as $order_item ) {

            if( 999 == $order_item[ 'product_id' ] ) {
                $user = new WP_User( $order->user_id );

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

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

        }

    }
} 

Note: Totally untested, but seems right in theory.

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