简体   繁体   中英

Display custom meta field value on Woocommerce email notifications

I am able to get meta field in cart and checkout pages, But in email I tried to get using $order array but don't find any custom field in email.

How can I get custom meta fields in email notificatios (Admin, Customer)?

My code is following:

function wdm_add_custom_order_line_item_meta($item, $cart_item_key, $values, $order)
{

    if(array_key_exists('wdm_name', $values))
    {
        $item->add_meta_data('_wdm_name',$values['wdm_name']);
    }
}

add_action( 'woocommerce_email_order_details', 'action_email_order_details', 10, 4 );
    function action_email_order_details( $order, $sent_to_admin, $plain_text, $email ) {
     if( $sent_to_admin ): // For admin emails notification

        echo get_post_meta( $order->id, '_wdm_name', true );

     endif;
}

Any help is appreciated.

You can achieve using following code.

Email code

 add_filter( 'woocommerce_email_order_meta_fields',    'woocommerce_email_order_meta_fields_func', 10, 3 );
 function woocommerce_email_order_meta_fields_func( $fields, $sent_to_admin, $order ) {

$fields['appointment_date'] = array(
    'label' => __( 'Wdm name', 'woocommerce' ),
    'value' => wptexturize( get_post_meta( $order->id, '_wdm_name', true ) )
);

$fields['appointment_time'] = array(
    'label' => __( 'Wdm Name', 'woocommerce' ),
    'value' => wptexturize( get_post_meta( $order->id, '_wdm_name', true ) )
);

//... more meta fields goes here

return $fields;
}

Admin side order add/edit page

add_action( 'woocommerce_email_after_order_table', 'woocommerce_email_after_order_table_func' );

function woocommerce_email_after_order_table_func( $order ) { ?>

<h3>Wdm Name (Custom field)</h3>
<table>
    <tr>
        <td>Date: </td>
        <td><?php echo wptexturize( get_post_meta( $order->id, '_wdm_name', true ) ); ?></td>
    </tr>
    <tr>
        <td>Time: </td>
        <td><?php echo wptexturize( get_post_meta( $order->id, '_wdm_name', true ) ); ?></td>
    </tr>
    <!--additional custom meta and HTML code goes here-->
</table>

<?php
}

Your code is just incomplete and not correct. Please replace it with the following:

add_action( 'woocommerce_checkout_create_order_line_item', 'custom_checkout_create_order_line_item', 20, 4 );
function custom_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
    if( isset( $values['wdm_name'] ) )
        $item->add_meta_data( __('Custom label'), $values['wdm_name'] );
}

Now once the order is placed (submitted) this custom field will appear everywhere on order items and on email notifications too… So you will not need anything else. You will just need to set the correct label for this custom field value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM