Hiding custom fields when content is empty

Having a hard time figuring this out. I created some custom checkout fields for my woocommerce checkout page. Then, I made the custom fields display on
the confirmation/thank you page. But my problem is that the field label still shows (in this case, “Order Details:”) even when the user did not submit info to the field. How can I make it so my custom fields only display when there is content to show? Or in other words, how can I hide the label when the field is empty?

/**
 * Add the field to the checkout (other details)
 */
add_filter ( 'woocommerce_checkout_fields', 'custom_override_checkout_fields6' );

function custom_override_checkout_fields6( $fields ) {

$fields['order']['other_details'] = array(

    'type'          => 'textarea',
    'class'         => array('extracheckoutinfo form-row-wide'),
    'label'         => __('Other Details'),
    'placeholder'   => __('Anything else we should know? Please provide as many details as possible.'),
    'required'      => false
    );

  return $fields;

}


/**
 * Update the order meta with field value 
 */
add_action( 'woocommerce_checkout_update_order_meta', 'other_details_field_update_order_meta' );

function other_details_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['other_details'] ) ) {
    update_post_meta( $order_id, 'Other Details', sanitize_text_field( $_POST['other_details'] ) );
}
}



/**
 * Add the fields to order confirmation/thank you page.
 **/

add_action( 'woocommerce_order_details_after_order_table', "my_woocommerce_other_details_after_order_table", 10, 1 );

function my_woocommerce_other_details_after_order_table( $order ) {

echo '<p><strong>'.__('Other Details').':</strong> ' . get_post_meta( $order->id, 'Other Details', true ) . '</p>';

}


/**
 * Display field value on the order edit page
 */
add_action( 'woocommerce_admin_order_data_after_billing_address', 'other_details_field_display_admin_order_meta', 10, 1 );

function other_details_field_display_admin_order_meta($order){
echo '<p><strong>'.__('Other Details').':</strong> ' . get_post_meta( $order->id, 'Other Details', true ) . '</p>';
}

Read more here: Hiding custom fields when content is empty

Leave a Reply

Your email address will not be published. Required fields are marked *