How to show WooCommerce custom product meta in new order emails?

1.3k Views Asked by At

I'm currently successfully saving custom post meta for a single product as follows:

    function save_payment_terms( $product_id ) {

        if ( isset( $_POST['payment_terms'] ) ) {
            update_post_meta( $product_id, 'payment_terms', is_numeric( $_POST['payment_terms'] ) ? absint( wp_unslash( $_POST['payment_terms'] ) ) : '1' );
        }

    }

How would I go about adding that custom post meta to a new order confirmation email? I've tried the following hooks without success: woocommerce_email_order_meta and woocommerce_order_item_meta_start. The latest iteration looking as follows:

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

function email_confirmation_display_order_items($item_id, $item, $order, $plain_text) {
    echo '<div>Terms: '. wc_get_order_item_meta( $item_id, 'payment_terms') .'</div>';

}

Resulting in: enter image description here

Doing a var_dump of wc_get_order_item_meta, I get: ../snippet-ops.php(446) : eval()'d code:7:boolean false

Anyone that could shed some light on this?

1

There are 1 best solutions below

1
On BEST ANSWER

Try the following instead:

add_action( 'woocommerce_order_item_meta_start', 'email_confirmation_display_order_items', 10, 3 );
function email_confirmation_display_order_items( $item_id, $item, $order ) {
    // On email notifications for line items
    if ( ! is_wc_endpoint_url() && $item->is_type('line_item') ) {
        $payment_terms = get_post_meta( $item->get_product_id(), 'payment_terms', true );

        if ( ! empty($payment_terms) ) {
            printf( '<div>' . __("Terms: %s", "woocommerce") . '</div>', $payment_terms );
        }
    }
}

Code goes in functions.php file of your active child theme (or active theme). It should works.

Related: WooCommerce Display avanced custom fields (ACF) inside order notification