【问题标题】:Change role after purchasing a specific product on WooCommerce在 WooCommerce 上购买特定产品后更改角色
【发布时间】:2017-10-19 05:27:04
【问题描述】:

我需要添加一个功能,在购买特定产品(按 ID 或类别)后更改用户角色。我该怎么做?

【问题讨论】:

    标签: wordpress woocommerce


    【解决方案1】:

    您可以使用此代码

    add_action( 'woocommerce_order_status_completed', 'misha_change_role_on_purchase' );
    
    function misha_change_role_on_purchase( $order_id ) {
    
    // get order object and items
    $order = new WC_Order( $order_id );
    $items = $order->get_items();
    
    $product_id = 55; // 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 role
                $user->remove_role( 'customer' ); 
    
                // Add role
                $user->add_role( 'subscriber' );
            }
    
    }
    
    }
    

    如果要按类别检查,只需添加条件has_term( $category_id, 'product_cat', $item['product_id'] )

    【讨论】:

    • 太棒了!非常感谢
    猜你喜欢
    • 2017-03-18
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2022-01-16
    • 2017-11-03
    • 2018-04-10
    相关资源
    最近更新 更多