成功下订单后,更改第n个订单上的用户角色

时间:2019-03-05 13:37:34

标签: php wordpress woocommerce hook-woocommerce

我以前实现了一个解决方案,用于更改注册时的用户角色,但是这次似乎丢失了一些东西。

外面有没有人对此有解决方案,或者能够针对我所缺少或做错的事情向我指出正确的方向?

是到目前为止我尝试过的。

add_action('woocommerce_thankyou', 'change_user_role_on_order_success');

function change_user_role_on_order_success($order_id ) {
 // Get all customer orders
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(),
        'post_type'   => 'shop_order', // WC orders post type
        'post_status' => 'wc-completed' // Only orders with status "completed"
    ) );
    // Count number of orders
    $count = count( $customer_orders );

     // return "true" when customer has already one order
    if ( $count >= 1 ) {
        $user = new WP_User( $order->get_user_id() );

        // our new role name
        $role = 'editor';

        //set the new role to our customer
           $user->set_role($role);
    }
}

1 个答案:

答案 0 :(得分:0)

也许您可以尝试使用钩子woocommerce_order_status_completed。您的客户真正完成订单后,它将立即触发,从而无需您检查状态。

function change_user_role_on_order_status_completed( $order_id ) {

    $order = new WC_Order( $order_id );

    $user_id = $order->user_id;

    $total_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => $user_id,
        'post_type'   => 'shop_order',
    ) );

    if ( $total_orders > 1 ) {
        $user = new WP_User( $order->user_id );

        // Set role editor
        $user->set_role( 'editor' );
    }
}

add_action( 'woocommerce_order_status_completed', 'change_user_role_on_order_status_completed', 10, 1 );