[英]Changing user role in WooCommerce on purchase
I'm working on WooCommerce with two product types.我正在使用两种产品类型开发 WooCommerce。 I need some of them ($products_to_check) to create an specific role account (subscriber) and the rest of them another one (customer, which is the default one for WooCommerce).我需要其中的一些($products_to_check)来创建一个特定的角色帐户(订阅者),其余的另一个(客户,这是 WooCommerce 的默认帐户)。
The thing is, if I have an user who's already a costumer, I don't want him to change its role to subscriber (so I check if he's logged in, which mean he's not a new costumer and have a previous defined role).问题是,如果我有一个已经是客户的用户,我不希望他将其角色更改为订阅者(因此我检查他是否已登录,这意味着他不是新客户并且具有以前定义的角色)。 On the other hand, if a subscriber purchase one of the products not included in $products_to_check, he should get a role upgrade (from subscriber to costumer).另一方面,如果订阅者购买了 $products_to_check 中未包含的产品之一,他应该获得角色升级(从订阅者到客户)。
This is my function, which is not working but I don't really know why.这是我的功能,它不起作用,但我真的不知道为什么。
add_action( 'woocommerce_order_status_completed', 'change_role_on_purchase' );
function change_role_on_purchase( $order_id ) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
$products_to_check = array( ... );
$user = new WP_User( $order->user_id );
$user_meta = get_userdata( $order->user_id );
$user_roles = $user_meta->roles;
foreach ( $items as $item ) {
if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) {
if (!is_user_logged_in()){
$user->set_role( 'subscriber' );
}
}
elseif ( $order->user_id > 0 && !(in_array( $item['product_id'], $products_to_check)) ) {
if (is_user_logged_in() && in_array('subscriber', $user_roles)){
$user->set_role( 'customer' );
}
}
}
}
I'd really appreciate any help on this issue.我真的很感激在这个问题上的任何帮助。 What am I doing wrong?我做错了什么?
There are several things you need to take note here.这里有几件事你需要注意。
user_register
is the hook to use for newly registered users. user_register
是用于新注册用户的钩子。So first make sure your hook triggers after or overrides the WooCommerce user role hooks.因此,首先确保您的钩子在 WooCommerce 用户角色钩子之后触发或覆盖。 And I think you can do away completely with the new or old user logic, as the only important thing is whether they purchased a product that's going to upgrade them;而且我认为你可以完全摒弃新的或旧的用户逻辑,因为唯一重要的是他们是否购买了要升级他们的产品; if not, they should have the default role.如果没有,他们应该具有默认角色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.