phpwordpresswoocommerceordersemail-notifications

WooCommerce add custom email content based on payment method, shipping method and shipping country


I would like to have a custom text e-mail sent to the customer according to the shipping they choose. we use shipping zones.

  1. Estonia - "Local pickup" - "custom_text_1" on order completed.
  2. Estonia - any other shipping method - current e-mail text remains as is.
  3. Anywhere outside Estonia but not "Flat rate" - "custom_text_2" on order completed.
  4. Any "Flat rate" type shipping - "custom_text_3" on order completed.

I believe it's called "Flat rate" or "Fixed rate" method by default? https://prnt.sc/FyDXD6NbMkSc

I've come across WooCommerce add custom email content based on payment method and shipping method answer thread.

Here is my code:

add_action( 'woocommerce_email_order_details', 'my_completed_order_email_instructions', 10, 4 );
function my_completed_order_email_instructions( $order, $sent_to_admin, $plain_text, $email ) {
    // Only for completed email notifications to customer
    if( 'customer_completed_order' != $email->id ) return;

    foreach( $order->get_items('shipping') as $shipping_item ){
        $shipping_rate_id = $shipping_item->get_method_id();
        $method_array = explode(':', $shipping_rate_id );
        $shipping_method_id = reset($method_array);
        // Display a custom text for local pickup shipping method only
        if( 'local_pickup' == $shipping_method_id ){
            echo '<p><strong>Ritiro in sede</strong></p>';
            break;
        }
    }
}

But this covers local shipping only.


Solution

  • Try the following instead:

    add_action( 'woocommerce_email_order_details', 'completed_order_email_custom_instructions', 10, 4 );
    function completed_order_email_custom_instructions( $order, $sent_to_admin, $plain_text, $email ) {
        // Only for "Customer Completed Order" email notification
        if( 'customer_completed_order' !== $email->id ) return;
    
        if ( $order->get_shipping_country() === 'EE' && $order->has_shipping_method('local_pickup') ){
            echo '<p><strong>'.__('Ritiro in sede').'</strong></p>';
        } elseif ( $order->get_shipping_country() !== 'EE' && ! $order->has_shipping_method('flat_rate') ){
            echo '<p><strong>'.__('custom text 2').'</strong></p>';
        } elseif ( $order->has_shipping_method('flat_rate') ){
            echo '<p><strong>'.__('custom text 3').'</strong></p>';
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). It should work.

    Related: