ninja08 ninja08 - 2 months ago 31
PHP Question

WooCommerce Email Filter

I am trying to dynamically add certain emails to the new order recipients list based on the customers ship-to address.

we are using PayPal advanced to process payments from within our site via n iframe.

The problem is that the filter that switches the email uses the customer's ship-to address which I am getting from one of two places:

$woocommerce->customer->shipping_country


$woocommerce->session->customer['shipping_country'];


Locally I don't have paypal advanced activated, so when test there it will work. However on the production server we are using it, and that's where the issue occurs. Those global objects are empty when the filter attempts to grab the customer's shipment order. This leads me to believe that once the PayPal order is done, the current page is redirected to the thank-you page with the proper information contained within it, however the global variables are empty when the filters are run.

With that said, how do I fetch the customer's shipping address info when
woocommerce_email_recipient_new_order
runs?

Answer

Once the order is placed you need to retrieve information (such as shipping country) from the $order object and not from the session. The order is passed to the woocommerce_email_recipient_new_order filter here as the second argument.

Here's an example of how you would pass the order object to your filter's callback and use it to modify the recipient:

function so_39779506_filter_recipient( $recipient, $order ){

    // get the shipping country. $order->get_shipping_country() will be introduced in WC2.7. $order->shipping_country is backcompatible
    $shipping_country = method_exists( $order, 'get_shipping_country') ) ? $order->get_shipping_country() : $order->shipping_country;

    if( $shipping_country() == 'US' ){
        $recipient = 'stack@example.com';
    }
    return $recipient;
}
add_filter( 'woocommerce_email_recipient_new_order', 'so_39779506_filter_recipient', 10, 2 );

Edited to make code compatible with both WooCommerce 2.7 and previous versions.