简体   繁体   中英

Woocommerce change role by total of user orders

I have a problem with php realization of automaticaly changing role of user. So i have custom role dovclient . First time user ordering get role Customer .

I need to change user role if he has buy products total 500$.

So i have a function

function wpa_120656_convert_paying_customer( $order_id ) {

  $order = new WC_Order( $order_id );

    $user_id = $order->user_id;

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

    $total = 0;
    foreach ( $customer_orders as $customer_order ) {
        $order = wc_get_order( $customer_order );
        $total += $order->get_total();
    }

    return $total;

    if ( $total > 500 ) {
       update_user_meta( $order->user_id, 'paying_customer', 1 );
        $user = new WP_User( $order->user_id );


        $user->remove_role( 'customer' ); 


       $user->add_role( 'dovclient10' );
    }
}
add_action( 'woocommerce_order_status_completed', 'wpa_120656_convert_paying_customer' );

I know, that $customer_orders are counting, and i make function working by count of orders. I mean if $customer_orders > 2 for ex., so change role.

But with total of order prices i have a problem. Role changes not. I don't know why. Maybe problem is in foreach ...

Please help me!

Amazing help! 0... ok. I have done it.

function wpa_120656_convert_paying_customer( $order_id ) {

  $order = new WC_Order( $order_id );

    $user_id = $order->user_id;

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

    $totall = 0;
    foreach ( $customer_orders as $customer_order ) {
    $order      = wc_get_order( $customer_order );
    $totall += $order->get_total();
    }

    if ( $totall > 500 ) {
        update_user_meta( $order->user_id, 'paying_customer', 1 );
       $user = new WP_User( $order->user_id );

        if( get_role('customer') ){
             $user->remove_role( 'customer' ); 
             $user->add_role( 'dovclient' );
        }
   }
}
add_action( 'woocommerce_order_status_completed', 'wpa_120656_convert_paying_customer' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM