skip to Main Content

In WooCommerce, I have added a product custom field (a product note) and it is displayed successfully in single product pages, under add to cart button.

How can I display that custom field value on admin order pages?

This is my field code:

add_action('woocommerce_after_add_to_cart_button', 'custom_product_note', 5 );
function custom_product_note() {
    global $product;

    if ( $product->is_type( 'variable' ) ) { 
        echo '<br><div style="margin-top:20px;">';

        woocommerce_form_field('product_note', array(
            'type' => 'textarea',
            'class' => array( 'my-field-class form-row-wide') ,
            'label' => __('Product Note - You can add up to 15 characters.') ,
            'maxlength' => ('15'),
            'placeholder' => __('Add a product note, please.') ,
            'required' => true,
        ) , '');

        echo '</div>';
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    thank you for answer. It was worked.


  2. First, you need the field value when adding to cart a product:

    add_filter( 'woocommerce_add_cart_item_data', 'save_product_note_as_cart_item_data', 10 );
    function save_product_note_as_cart_item_data( $cart_item_data ) {
        if ( isset($_POST['product_note']) ) {
            $cart_item_data['product_note'] = esc_attr($_POST['product_note']);
            $cart_item_data['unique_key'] = md5( microtime().rand() );
    
            // Display a message notice (optional)
            wc_add_notice( __("The product note has been saved successfully", "woocommerce"));
        }
        return $cart_item_data;
    }
    

    Then you need to save this custom product note in the order data (specifically in the order item as custom metadata):

    add_action( 'woocommerce_checkout_create_order_line_item', 'save_and_display_on_admin_edit_order', 10, 4 );
    function save_and_display_on_admin_edit_order( $item, $item_key, $values, $order ) {
        if ( isset($values['product_note']) ) {
            $item->add_meta_data( '_product_note', $values['product_note'] );
        }
    }
    
    // Add readable "meta key" label name replacement
    add_filter('woocommerce_order_item_display_meta_key', 'filter_wc_order_item_display_meta_key', 10, 3 );
    function filter_wc_order_item_display_meta_key( $display_key, $meta, $item ) {
        if( is_admin() && $item->get_type() === 'line_item' && $meta->key === '_product_note' ) {
            $display_key = __('Note', 'woocommerce');
        }
        return $display_key;
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search