Woocommerce:订单完成后更改用户角色 [英] Woocommerce: changing user role when order is complete

查看:66
本文介绍了Woocommerce:订单完成后更改用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 wordpress 与 woocommerce 结合使用,我想自动化以下步骤.订单完成后,我想将与该订单 ID 关联的用户角色从客户"更改为订阅者".

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'.


通过四处寻找,我认为我应该能够通过在functions.php中使用钩子来实现这一点:

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

然后添加函数:

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


在代码中,我认为我需要做两件事:
1) 获取与该订单 ID 关联的用户 ID
2) 将该用户 ID 的角色更改为订阅者

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


我已经尝试了很多,但我无法让它工作(既没有获得正确的用户 ID,也没有改变用户 ID 的角色).所以任何帮助将不胜感激!我在堆栈溢出之前看到过 2 个相关的问题,但不幸的是那里的答案对我不起作用.希望有人能帮帮我!

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!

非常感谢!:)

推荐答案

Helgatheviking from wordpress answers 想出了这段代码:

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

function wpa_120656_convert_paying_customer( $order_id ) {

$order = wc_get_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! :)

这篇关于Woocommerce:订单完成后更改用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆