Development WooCommerce Wordpress

How to display item meta data in email confirmation using woocommerce_order_item_meta_end

Our store sells software and we’re adding a software voucher code to each purchased. Once the purchase is completed (via the woocommerce_payment_complete hook) we generate the voucher code and add it to each item purchased via wc_add_order_item_meta method.

Summarized code:

add_filter('woocommerce_payment_complete', 'add_voucher_code');

function add_voucher_code( $order_id ) {

    $order = new WC_Order( $order_id );
    $items = $order->get_items();

    foreach ($items as $item)   {

        for ($i = 1; $i <= $item['qty']; $i++)  {
            $voucher_code = 'API request based on order information to get voucher code';
            wc_add_order_item_meta($item->get_id(), 'Voucher Code', $voucher_code);

For some reason or another the item custom meta shows up on the order confirmation page, but doesn’t in the confirmation email. (problem 1 slaps forehead) So we’re utilizing the woocommerce_order_item_meta_end hook to add it to the confirmation email. (wc_get_order_item_meta)

Summarized code:

add_action('woocommerce_order_item_meta_end', 'email_confirmation_display_order_items', 10, 4);

function email_confirmation_display_order_items($item_id, $item, $order, $plain_text) {

    echo '<div>Voucher Code: '. wc_get_order_item_meta( $item_id, 'Voucher Code') .'</div>';

Problem 2 is that added snippet of code shows on the both the order confirmation page (so now it shows twice) and in the order confirmation email. (slaps forehead again)

Current Problem 2 Solution
Right now we solved it by adding an if statement which is suggested here. Like so:

// Only on emails notifications
if( ! (is_admin() || is_wc_endpoint_url() )) {
    echo '<div>Voucher Code: '. wc_get_order_item_meta( $item_id, 'Voucher Code') .'</div>';

This feels like a band-aid fix and any insight/suggestions would be much appreciated. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *