最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

woocommerce offtopic - Removing unwanted role after purchase

programmeradmin1浏览0评论

I have the following code which is changing the user role from out_of_time to learner_member on purchase of the product 16323 - this works fine.

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 ( current_user_can( 'out_of_time' ) && $product_id == '16323' ) {
            update_user_meta( $order->user_id, 'paying_customer', 1 );
            $user = new WP_User( $order->user_id );

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

            // Add role
            $user->add_role( 'learner_member' );
        }
    
    else {
        return true;
    }

    }
}

add_action( 'woocommerce_order_status_processing', 'change_role_on_purchase' );

However when I look at the user afterwards they have primary role of learner_member AND subscriber is added as "Other Roles".

How can I prevent subscriber from being added at all.

I have the following code which is changing the user role from out_of_time to learner_member on purchase of the product 16323 - this works fine.

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 ( current_user_can( 'out_of_time' ) && $product_id == '16323' ) {
            update_user_meta( $order->user_id, 'paying_customer', 1 );
            $user = new WP_User( $order->user_id );

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

            // Add role
            $user->add_role( 'learner_member' );
        }
    
    else {
        return true;
    }

    }
}

add_action( 'woocommerce_order_status_processing', 'change_role_on_purchase' );

However when I look at the user afterwards they have primary role of learner_member AND subscriber is added as "Other Roles".

How can I prevent subscriber from being added at all.

Share Improve this question edited Feb 5 at 21:55 vancoder 7,92428 silver badges35 bronze badges asked Feb 5 at 16:08 Adam OXenham SmithAdam OXenham Smith 51 bronze badge 1
  • the line with add_role should remove all other roles then I think that woocommerce is doing something special. so you have to ask woocommerce developers. – mmm Commented Feb 6 at 6:10
Add a comment  | 

1 Answer 1

Reset to default 0

Just use $user->set_role( 'learner_member' ); instead of both lines where you are removing and adding the role.

Link to the docs.

发布评论

评论列表(0)

  1. 暂无评论