簡體   English   中英

在 WooCommerce 中購買時自動更改用戶角色

[英]Automatically changing user role upon purchase in WooCommerce

我想為已經完成購買的 WooCommerce 客戶創建一個僅限會員的部分,為他們分配一個新角色,因為所有注冊用戶的默認角色都是“客戶”。

我偶然發現了一些可以解決這個問題的代碼,但是商店中有 200 多種產品,單獨列出所有產品會很麻煩。

無論如何,是否可以為進行任何購買的客戶提供新角色?

這是原始代碼:

add_action( 'woocommerce_order_status_completed', 'wpglorify_change_role_on_purchase' );

function wpglorify_change_role_on_purchase( $order_id ) {

// get order object and items
    $order = new WC_Order( $order_id );
    $items = $order->get_items();

    $product_id = 56; // that's a specific product ID

    foreach ( $items as $item ) {

        if( $product_id == $item['product_id'] && $order->user_id ) {
            $user = new WP_User( $order->user_id );

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

            // Add new role
            $user->add_role( 'editor' );
        }
    }
}

更新

您可以改用以下內容,這將在客戶成功購買(已付款訂單)時更改用戶角色:

add_action( 'woocommerce_order_status_processing', 'change_role_on_purchase', 10, 2 );
add_action( 'woocommerce_order_status_completed', 'change_role_on_purchase', 10, 2 );
function change_role_on_purchase( $order_id, $order ) {
    $user = $order->get_user(); // Get the WP_User Object

    // Check for "customer" user roles only
    if( is_a( $user, 'WP_User' ) && in_array( 'customer', (array) $user->roles ) ) {
        // Remove WooCommerce "customer" role
        $user->remove_role( 'customer' ); 

        // Add new role
        $user->add_role( 'editor' );
    }
}

代碼位於活動子主題(或活動主題)的 functions.php 文件中。 測試和工作。

注意: WC_Order對象已經是該掛鈎函數的現有參數(您的代碼中缺少)。


添加:刪除所有以前的角色並分配新角色

這可以僅使用WP_User set_role()方法,因此在代碼中,替換:

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

// Add new role
$user->add_role( 'editor' );

經過:

// Reset user roles and set a new one
$user->set_role( 'editor' );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM