questions

Displaying a second custom field on WooCommerce email notifications

Rate this post

I have added two custom fields to my WooCommerce checkout page. I managed to get them to show up on the front end, and on the back end.

The next step is to get the fields to display in the order emails. I found this piece of code for the phone number which works perfectly for the phone number custom field:

add_filter( 'woocommerce_email_order_meta_fields', 'custom_woocommerce_email_order_meta_fields', 10, 3 );

function custom_woocommerce_email_order_meta_fields($fields, $sent_to_admin, $order) {
    $fields['meta_key'] = array(
        'label' => __( 'Shipping Phone' ),
        'value' => get_post_meta( $order->id, '_shipping_phone', true ),
    );
return $fields;
}

BUT this code is written for one field and works to show only the phone number field.

Now I need to adjust the code to show also the email field. I tried like this below but it REPLACES the Phone number field with the email field instead of adding both.

What am I doing wrong?

 add_filter( 'woocommerce_email_order_meta_fields', 'custom_woocommerce_email_order_meta_fields', 10, 3 );

function custom_woocommerce_email_order_meta_fields($fields, $sent_to_admin, $order) {
    $fields['meta_key'] = array(
        'label' => __( 'Shipping Phone' ),
        'value' => get_post_meta( $order->id, '_shipping_phone', true ),
    );     // I also tried to replace this ; with , but it returned an error //
    $fields['meta_key'] = array(
        'label' => __( 'Shipping Email' ),
        'value' => get_post_meta( $order->id, '_shipping_email', true ),
    );*/
return $fields;
} 

 

✔️Solution:

You’re missing the correct meta_key

Use it like this instead:

function custom_woocommerce_email_order_meta_fields( $fields, $sent_to_admin, $order ) {
    // Get meta
    $shipping_phone = $order->get_meta( '_shipping_phone', true );
    
    // NOT empty
    if( ! empty( $shipping_phone ) ) {  
        $fields['_shipping_phone'] = array(
            'label' => __( 'Shipping Phone' ),
            'value' => $shipping_phone,
        );
    }
    
    // Get (other) meta
    $shipping_email = $order->get_meta( '_shipping_email', true );
    
    // NOT empty
    if ( ! empty( $shipping_email ) ) { 
        $fields['_shipping_email'] = array(
            'label' => __( 'Shipping Email' ),
            'value' => $shipping_email,
        );
    }
    
    return $fields;
}
add_filter( 'woocommerce_email_order_meta_fields', 'custom_woocommerce_email_order_meta_fields', 10, 3 );

Leave a Reply

Your email address will not be published.

Back to top button