Add a custom field (in an order) to the emails

Posted on
5/5 - (252 votes)

You can add any custom field to your order emails by hooking in and specifying the name of the custom field. This can be useful if, for example, you want to include things like the ‘transaction key’ from PayPal orders.

Alternatively, you can add the code snippet using Code Snippet plugin.

/**
 * Add a custom field (in an order) to the emails
 */
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' => __( 'Label' ),
        'value' => get_post_meta( $order->id, 'meta_key', true ),
    );
    return $fields;
}

Here is an example using a custom field that was added with the Checkout Field Editor extension. As of version 1.1.8 the code is no longer required for the extension’s own fields, but the code is still valid for custom fields created in other ways.

In this example, a custom field with the label hear_about_us was added:

To add the newly added custom field hear_about_us to the order email, the code would look like this:

/**
 * Add a custom field (in an order) to the emails
 */
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['hear_about_us'] = array(
        'label' => __( 'Hear About Us' ),
        'value' => get_post_meta( $order->id, 'hear_about_us', true ),
    );
    return $fields;
}