Search code examples
phpwordpresswoocommercelocationemail-notifications

WooCommerce New Order email recipient based on Customer Billing State


I adapted an old snippet (2 Years) code found on Business Bloomer to redirect a new order email notification based on the customer country, to fit my need of redirect it to a couple of people, one the sales person and the manager, based on the customer's Billing State instead.

I came up with the following code, but is not working as WooCommerce isn't sending the mail notification.

// PART 1
// Define an array with the state and the intended recepient
// States Codes belong to Mexico states 
 
function matriz_estados( $ubica_estado ) {
   $destinatarios = array(
      'MO' => '[email protected], [email protected]',
      'CL' => '[email protected], [email protected]',
      'GT' => '[email protected], [email protected]',',

      //etc       
      
   );
   return $destinatarios[$ubica_estado];
}
 
// PART 2
// Extract Order billing state and correlate with array to define email recipients 

add_filter( 'woocommerce_email_recipient_new_order', 'define_receptor', 9999, 3 );
 
function define_receptor( $email_recipient, $order_object, $email ) {
   if ( is_admin() ) return $email_recipient;
   if ( $order_object && $ubica_estado = $order_object->get_billing_state() ) {
      $email_recipient = matriz_estados( $ubica_estado );
   }
   return $email_recipient;
}

Is there an error? is something not supposed to be in it?

Any ideas, suggestions and corrections are welcome.


Solution

  • There are some mistakes and missing things in your code.

    Try the following instead:

    
    // Utility function: Get a recipient based on state code
    function get_recipient_for_state( $state ) {
        // Define your array of state code and email(s) pairs
        $data = array(
            'MO' => '[email protected],[email protected]',
            'CL' => '[email protected],[email protected]',
            'GT' => '[email protected],[email protected]',
        );
        // Check if the customer state matches 
        return array_key_exists($state, $data) ? $data[$state] : '';
     }
      
    // New order recipient based on customer billing state
    add_filter( 'woocommerce_email_recipient_new_order', 'new_order_recipient_based_on_state', 9999, 3 );
    function new_order_recipient_based_on_state( $recipient, $order, $email ) {
        if ( is_admin() || !$order ) return $recipient;
    
        $recipient_for_state = get_recipient_for_state( $order->get_billing_state() );
    
        return $recipient_for_state ? : $recipient;
    }
    

    It should work.