Woocommerce: changing user role when order is complete

旧巷老猫 提交于 2019-12-05 08:02:09

问题


I'm using wordpress with woocommerce, and I would like to automate the following step. When an order is completed, I would like to change the user role associated with that order id from 'customer' to 'subscriber'.


By searching around, I think I should be able to accomplish this by using a hook in functions.php:

add_action( 'woocommerce_order_status_completed', 'change_role_from_customer_to_subscriber' );

Then add the function:

function change_role_from_customer_to_subscriber($order_id){
// code to change role to subscriber
}


In the code, I think I need to do 2 things:
1) get the user id that is associated with that order id
2) change role of that user id to subscriber


I've tried a lot, but I couldn't get it to work (neither getting the right user id, nor changing the role of a user id). So any help would be appreciated! I've seen 2 related questions asked before on stack overflow, but unfortunately the answers there did not work for me. I hope someone can help me out!

Thanks a lot! :)


回答1:


Helgatheviking from wordpress answers came up with this piece of code:

function wpa_120656_convert_paying_customer( $order_id ) {

$order = new WC_Order( $order_id );

if ( $order->user_id > 0 ) {
    update_user_meta( $order->user_id, 'paying_customer', 1 );
    $user = new WP_User( $order->user_id );

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

    // Add role
    $user->add_role( 'subscriber' );
}
}
add_action( 'woocommerce_order_status_completed', 'wpa_120656_convert_paying_customer' );


For some unknown reason it took several tries, but it worked! Thanks everyone for the help! :)




回答2:


You could do the following:

$current_user = wp_get_current_user(); 
$user_data = array(
            'ID' => $current_user->ID,
            'role' => 'New Role Here' 
        );
wp_update_user( $user_data );  

Add this to your above function, and it will do the trick.



来源:https://stackoverflow.com/questions/19681523/woocommerce-changing-user-role-when-order-is-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!