0
votes

I have an issue trying to make a hook on the WooCommerce plugin for WordPress. The problem is that I need to conditionally change the recipient email of the order depending on the local pickup shipping option they choose. My code was working properly for months, but suddenly; it stopped working. This is what I have on my functions.php file:

    add_filter( 'woocommerce_email_recipient_new_order', 'diff_recipients_email_notifications', 10, 2 );
function diff_recipients_email_notifications( $recipient, $order ) {

    $shippingOptionOne = '[email protected]';
    $shippingOptionTwo = '[email protected]';
    $shippingOptionThree = '[email protected]';

    $order_shipping = $order->get_items('shipping');
    $key = key($order_shipping);
    $shipping_method_id = $order_shipping[$key]['item_meta']['method_id'][0];

    if($shipping_method_id == 'local_pickup:6' )
    {
        $recipient = $shippingOptionOne;
    }
    elseif($shipping_method_id == 'local_pickup:4'){
        $recipient = $shippingOptionTwo;
    }
    elseif($shipping_method_id == 'local_pickup:7'){
        $recipient = $shippingOptionThree;
    }
    return $recipient;
}

I've made some testing and research and after debugging a little bit, I've came to the conclusion that the variable $order which is coming as the second parameter of my function is printing an empty value, so I can't get the $order_shipping = $order->get_items('shipping'); ($order is printing an empty space).

Thanks in advance.

P.S: This is the link I used to make my code in first place: WooCommerce email notifications: different email recipient for different cities

1

1 Answers

0
votes

My team and I spent some time debugging and we came to the solution. For some reason, the var_dump wasn't printing the order but it was there, we just changed this line:

$order_shipping = $order->get_items('shipping');
    $key = key($order_shipping);
    $shipping_method_id = $order_shipping[$key]['item_meta']['method_id'][0];

and replaced it with this one:

$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0];

Of course we also changed

$shipping_method_id

with:

$chosen_shipping

And it works as a charm!