Search code examples
phpwordpresswoocommercecustom-fieldsorders

Display Woocommerce order metadata value in a readonly input text field


I am using the snippet from a larger piece of (beautiful) code that I got from an answer provided by @LoicTheAztec here : WooCommerce : Add custom Metabox to admin order page

// Display field value on the order edit page (not in custom fields metabox)
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta($order){
$my_custom_field = get_post_meta( $order->id, '_my_field_slug', true );
if ( ! empty( $my_custom_field ) ) {
echo '<p><strong>'. __("My Field", "woocommerce").':</strong> ' . get_post_meta( $order->id, '_my_field_slug', true ) . '</p>';}
}

By learning about custom attributes, through other questions I found, I know I can make a text field read only by adding array('readonly' => 'readonly') but not sure how I could implement that (if possible) to the above snippet. Any help would be greatly appreciated and thank you in advance!


Solution

  • Try the following replacement with a readonly input field (for Woocommerce 3+):

    add_action( 'woocommerce_admin_order_data_after_billing_address', 'custom_field_value_display_on_admin_order', 10, 1 );
    function custom_field_value_display_on_admin_order( $order ){
        if ( $value = $order->get_meta('_my_field_slug') ) {
            echo '<p class="form-field"><label for=""><strong>'. __("My Field", "woocommerce").':</strong></label>
            <input type="text" name="my_field_slug" value="' . $value . '" readonly></p>';
        }
    }
    

    on function.php file of your active child theme (or active theme). Tested and works.

    enter image description here