Woocommerce 在购买时更改用户角色 [英] Woocommerce change user role on purchase

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

问题描述

我正在尝试使用这段代码将我的用户从订阅者"的默认角色更新为从我的商店购买产品时的高级"角色.

I am trying to use this snippet of code to update my users from the default role of 'Subscriber' to the role of 'Premium' on the purchase of a product from my store.

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

foreach ( $items as $item ) {
    if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) {
        $user = new WP_User( $order->user_id );

        // Change role
        $user->remove_role( 'Subscriber' );
        $user->add_role( 'Premium' );

        // Exit the loop
        break;
    }
}
}

我的商店中只有 1 件产品,它的产品 ID 为 416(我已将其插入代码中).

I only have 1 product in my store and it has the product ID 416 (which I have inserted in the code).

我已经把它放到了functions.php 中,但我没有任何运气.任何成功购买后,角色都不会更新.有什么想法吗?

I have put this into functions.php, but i'm not having any luck. The role isn't being updated after any successful purchase. Any ideas?

推荐答案

试试这个:

function change_role_on_purchase( $order_id ) {

    $order = new WC_Order( $order_id );
    $items = $order->get_items();

    foreach ( $items as $item ) {
        $product_name = $item['name'];
        $product_id = $item['product_id'];
        $product_variation_id = $item['variation_id'];

        if ( $order->user_id > 0 && $product_id == '416' ) {
            update_user_meta( $order->user_id, 'paying_customer', 1 );
            $user = new WP_User( $order->user_id );

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

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

add_action( 'woocommerce_order_status_processing', 'change_role_on_purchase' );

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

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