1

I used WC Field factory to generate some custom fields including a textbox called "message_to_recipient." I want to pass this to the email that goes out.

In my functions.php, I am using this:

add_action( 'woocommerce_email_before_order_table', 'add_order_email_instructions', 10, 2 );

function add_order_email_instructions( $order, $sent_to_admin ) {

 $custom_message = get_post_meta( $order->ID, "message_to_recipient", true );

 if ( ! $sent_to_admin ) {

 echo '<h2>You received a gift Card from '.$order->billing_first_name .' '.$order->billing_last_name.'</h2>';
 echo '<p><strong>Message:</strong> ' . $custom_message. '</p>'; 

}

The first echo, call to $order->billing_first_name etc. works fine. But the second one doesn't.

having used WC Field Factory, am I simply not using the right name, or is this the wrong hook to grab the meta data from the order?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
bamabacho
  • 191
  • 2
  • 16

1 Answers1

1

To get the Order ID from the WC_Order object, since WooCommerce version 3+ you should need to use get_id() method.

Also you should better use WC_Order methods as get_billing_last_name() and get_billing_last_name() instead…

So your code should be:

add_action( 'woocommerce_email_before_order_table', 'add_order_email_instructions', 10, 2 );
function add_order_email_instructions( $order, $sent_to_admin ) {
    if ( ! $sent_to_admin ) {
        // compatibility with WC +3
        $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
        $first_name = method_exists( $order, 'get_billing_first_name' ) ? $order->get_billing_first_name() : $order->billing_first_name;
        $last_name = method_exists( $order, 'get_billing_last_name' ) ? $order->get_billing_last_name() : $order->billing_last_name;

        $custom_message = get_post_meta( $order_id , "message_to_recipient", true );

        echo '<h2>You received a gift Card from '. $first_name .' '. $last_name .'</h2>';

        if( ! empty($custom_message) )
            echo '<p><strong>Message:</strong> ' . $custom_message. '</p>'; 
    } 
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This should work for you now (on any WC version since WC 2.5+)


Related thread related to Orders: How to get WooCommerce order details

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • 1
    Thanks. I must be using the wrong field name. he rest of this code, with updated methods, works. – bamabacho Nov 07 '17 at 21:25
  • 1
    I replaced the key argument in the get_post_meta function to something else and the code works, its just the key name "message_to_recipient must be wrong – bamabacho Nov 07 '17 at 21:35