Lgane
Lgane

Reputation: 97

Woocommerce Switch User Role based on customer total purchases amount

I'm using the code from here.

It changes the user's role after reaching the purchase amounts. My attempts to expand it and check some conditions:

  1. The amount of the period during which purchases must be verified is 2 years. if over a period of 2 years the amount of purchases is not equal to 5000, then the status must be recalculated again and a role must be assigned to him in accordance with his order amount. Here are the amounts I plan to use:

$threshold_amount_to_silver = 4999.99;

$threshold_amount_to_gold = 9999.99;

$threshold_amount_to_platinum = 14999.99;

  1. The amount of purchases should include only orders that have a completed status, and if orders were canceled or their status is somehow different from the completed status, then the amount should be reduced and the order status recalculated again. If a return was made, the purchase amount must be reduced by the refund amount.
  2. Recalculation occurs only among the roles: subscriber, customer, karta-silver, karta-gold, karta-platinum.

I tried to add my own changes to the code using the silver condition as an example. But it does not work and the roles are not recalculated. Any help please.

function bbloomer_maybe_trigger_switch_user_role( $order_id ) {
   $order = wc_get_order( $order_id );
   $user_id = $order->get_user_id();
   $order_status = $order->get_status();
   $switch_already_done = $order->get_meta( '_bb_role_switched' );

   $roles_to_check = array( 'subscriber', 'customer', 'karta-platinum', 'karta-gold', 'karta-silver' );
   if ( ! $switch_already_done && $order->has_status( wc_get_is_paid_statuses() ) ) {
      foreach ( $roles_to_check as $role ) {
         if ( wc_user_has_role( $user_id, $role ) ) {
            bbloomer_customer_maybe_upgrade_to_silver( $user_id );
            $order->update_meta_data( '_bb_role_switched', 'true' );
            $order->save();
            break; 
         }
      }
   }
}

function bbloomer_customer_maybe_upgrade_to_silver( $user_id ) {
   $threshold_amount_to_silver = 4999.99; 
   $threshold_date  = date('Y-m-d', strtotime('-2 years')); 
   $total_spent = wc_get_customer_total_spent( $user_id, $threshold_date ); 
   if ( $total_spent > $threshold_amount_to_silver ) {
      $user = new WP_User( $user_id );
      $user->add_role( 'karta-silver' );
      $user->remove_role( 'subscriber' );
      $user->remove_role( 'customer' );
      $user->remove_role( 'karta-gold' );
      $user->remove_role( 'karta-platinum' );
   }
}

Upvotes: 0

Views: 124

Answers (0)

Related Questions