doukui9491 2017-06-27 01:09
浏览 10
已采纳

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;
    }
}
}

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

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?

  • 写回答

3条回答 默认 最新

  • doukeyong3746487 2017-06-27 06:31
    关注

    Have a try with this one:

    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' );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器