[英]Changing user role in WooCommerce on purchase
我正在使用两种产品类型开发 WooCommerce。 我需要其中的一些($products_to_check)来创建一个特定的角色帐户(订阅者),其余的另一个(客户,这是 WooCommerce 的默认帐户)。
问题是,如果我有一个已经是客户的用户,我不希望他将其角色更改为订阅者(因此我检查他是否已登录,这意味着他不是新客户并且具有以前定义的角色)。 另一方面,如果订阅者购买了 $products_to_check 中未包含的产品之一,他应该获得角色升级(从订阅者到客户)。
这是我的功能,它不起作用,但我真的不知道为什么。
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' );
}
}
}
}
我真的很感激在这个问题上的任何帮助。 我做错了什么?
这里有几件事你需要注意。
user_register
是用于新注册用户的钩子。因此,首先确保您的钩子在 WooCommerce 用户角色钩子之后触发或覆盖。 而且我认为你可以完全摒弃新的或旧的用户逻辑,因为唯一重要的是他们是否购买了要升级他们的产品; 如果没有,他们应该具有默认角色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.