Custom field value disappears after update

Viewed 65

I have added a custom field to my order details page, and echo this value to a custom field. The problem I have is that the value disappears if I update the page. How do I make the value stay?

I assume this is because the textfield is empty. Can I check for it and dont update if it is? Or keep the value in the textfield.

add_action( 'woocommerce_admin_order_data_after_order_details', 
'custom_woocommerce_admin_order_data_after_order_details' );
function custom_woocommerce_admin_order_data_after_order_details( $order ){
?>

<?php 
 $custom_field_value = get_post_meta( $order->id, 'my_custom_field_name', true);
?>


<div class="edit_custom_field"> 
<?php
    woocommerce_wp_textarea_input( array(
        'id' => 'custom_field_name',
        'label' => 'Add serial number here:',
        'value' => $custom_field_value,
        'wrapper_class' => 'form-field-wide'
    ) );
    
?>   
</div>
    
<?php
}


 add_action( 'woocommerce_process_shop_order_meta', 
 'custom_woocommerce_process_shop_order_meta' );
 function custom_woocommerce_process_shop_order_meta( $order_id ){
 update_post_meta( $order_id, 'custom_field_name', wc_sanitize_textarea( $_POST[ 
 'custom_field_name' ] ) );
 }

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){
echo '<p><strong>'.__('Serial number').':</strong> <br/>' . get_post_meta( $order->get_id(), 'custom_field_name', true ) . '</p>';           
}
0 Answers
Related