[英]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.