当内容为空时隐藏自定义字段

时间:2017-04-25 作者:kosmicbird

很难弄明白这一点。我为我的woocommerce签出页面创建了一些自定义签出字段。然后,我将自定义字段显示在确认/感谢页面上。但我的问题是,即使用户没有向字段提交信息,字段标签仍然显示(在本例中为“订单详细信息:”)。如何使自定义字段仅在有内容显示时显示?或者换句话说,当字段为空时,如何隐藏标签?

/**
 * 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>\';
}

1 个回复
最合适的回答,由SO网友:kosmicbird 整理而成

明白了!

我需要添加这一行:

if ( $other_details = get_post_meta( $order->id, \'Other Details\', true ) ) {
因此,我需要更改的块的完整代码是:

/**
 * 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 ) {

 if ($other_details = get_post_meta( $order->id, \'Other Details\', true ) ) {

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

    }

}    

相关推荐

如何让`wp-list-table`显示我在Custom-Post中的`Custom-Fields`

一切都好吗<我需要wp-list-table 也要显示custom-fields 在每个custom-post 我有,但我不知道如何做到这一点,在这幅图中,它显示了带有字段的表格:Title, Author and Publication Date: 我想要的是能够选择custom-fields 将出现,例如以下示例Title, Carta, Naipe, Author, and Date of Publication: