Search code examples
phpwordpresswoocommerceordersemail-notifications

Display a product custom field value in Woocommerce admin email notifications


I have this code in my function.php, how can i dispaly this field value in admin mail order? Thanks!

//1.1 Display field in admin
add_action('woocommerce_product_options_inventory_product_data', 'woocommerce_product_custom_fields');
function woocommerce_product_custom_fields(){
    global $woocommerce, $post;
    echo '<div class="product_custom_field">';
    woocommerce_wp_text_input(
        array(
            'id' => '_custom_product_text_field',
            'placeholder' => 'Name',
            'label' => __('customtext', 'woocommerce'),
            'desc_tip' => 'true'
        )
    );    
    echo '</div>';
}

//1.2 Save field
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');
function woocommerce_product_custom_fields_save($post_id){
    $woocommerce_custom_product_text_field = $_POST['_custom_product_text_field'];
    if (!empty($woocommerce_custom_product_text_field))
        update_post_meta($post_id, '_custom_product_text_field', esc_attr($woocommerce_custom_product_text_field));

}

Solution

  • Update 2 There is two very similar alternatives (the first one is better):

    To display easily this product custom field values in emails (and in orders too) you can use the following code, that will save this data in order items, once the order is placed.

    First alternative code (the best new one that use WC 3+ recent CRUD methods):

    // 1.3 Save custom field value in order items metadata (only for WooCommerce versions 3+)
    add_action( 'woocommerce_checkout_create_order_line_item', 'add_custom_field_to_order_item_meta', 20, 4 );
    function add_custom_field_to_order_item_meta( $item, $cart_item_key, $values, $order ) {
        $custom_field_value = get_meta( $item->get_product_id(), '_custom_product_text_field' );
        if ( ! empty($custom_field_value) ){
                $item->update_meta_data( __('Custom label', 'woocommerce'), $custom_field_value );
        }
    }
    

    … or …

    The other alternative (the old one updated):

    // 1.3 Save custom field value in order items meta data
    add_action( 'woocommerce_add_order_item_meta', 'add_custom_field_to_order_item_meta', 20, 3 );
    function add_custom_field_to_order_item_meta( $item_id, $values, $cart_item_key ) {
    
        $custom_field_value = get_post_meta( $values['data']->get_id(), '_custom_product_text_field', true );
        if ( ! empty($custom_field_value) )
            wc_add_order_item_meta( $item_id, __('Custom label', 'woocommerce'), $custom_field_value );
    }
    

    Code goes in function.php file of your active child theme (or theme). Tested and works.

    On orders you will get that (for both):

    enter image description here

    On emails you will get that (for both):

    enter image description here