Output product custom field values in order email notification

懵懂的女人 提交于 2021-02-08 08:36:10

问题


I have a custom field for a Woocommerce's product, and I want to display it's value in order emails.

As I'm using custom product submission form, I added this code for custom field below to create a custom field:

<?php 
    WCVendors_Pro_Form_Helper::select( array(  
        'post_id'       => $object_id,
        'class'         => 'select2',
        'id'            => 'wcv_custom_product_ingredients', 
        'label'         => __( 'What time?', 'wcvendors-pro' ), 
        'placeholder'   => __( 'Pick a time', 'wcvendors-pro' ),
        'wrapper_start' => '<div class="all-100">',
        'wrapper_end'   => '</div>',
        'desc_tip'      => 'true', 
        'description'   => __( 'Pick a time', 'wcvendors-pro' ),
        'options'       => array( '12:00 midnight' => __('12:00 midnight', 'wcv_custom_product_ingredients'), '12:15 midnight'=> __('12:15 midnight', 'wcv_custom_product_ingredients') )
) );
?>

I also tried adding code below to functions.php, but this only displays "What time?" without value in order emails...

add_action('woocommerce_email_after_order_table', 'wcv_ingredients_email');
function wcv_ingredients_email() {
    $output = get_post_meta( get_the_ID(), 'wcv_custom_product_ingredients', true );
    echo 'What time? ' . $output . '<br>';
}

What could be the issue?


回答1:


You are using the correct hook, but you just forgot the hook arguments in the hooked function.

Also as you are targeting a product custom field value, and as in an order you can have many items (products), the code below will display this value for each order item.

Try the code below, it works now:

// Tested on WooCommerce version 2.6.x and 3+ — For simple products only.
add_action('woocommerce_email_after_order_table', 'wcv_ingredients_email', 10, 4);
function wcv_ingredients_email( $order,  $sent_to_admin,  $plain_text,  $email ){
    foreach($order->get_items() as $item_values){
        // Get the product ID for simple products (not variable ones)
        $product_id = $item_values['product_id'];
        $output = get_post_meta( $product_id, 'wcv_custom_product_ingredients', true );
        echo 'What time? ' . $output . '<br>';
    }
}

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



来源:https://stackoverflow.com/questions/43393500/output-product-custom-field-values-in-order-email-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!