在Woocommerce中,我使用了@LoicTheAztec的Add a new custom checkout field before billing details in Woocommerce?,效果很好。
我在管理订单页面上显示信息时遇到问题。
然后我尝试使用Add order metadata to WooCommerce admin order overview,对代码进行一些更改以满足我的需求:
// display the extra data in the order admin panel
function kia_display_order_data_in_admin( $order ){ ?>
<div class="order_data_column">
<h4><?php _e( 'Extra Details' ); ?></h4>
<?php
echo '<p><strong>' . __( 'Some field' ) . ':</strong>' . get_post_meta( $order->id, '_my_field_name', true ) . '</p>';?>
</div>
<?php }
add_action( 'woocommerce_admin_order_data_after_order_details', 'kia_display_order_data_in_admin' );?>
其他详细信息和某些字段:出现,但自定义字段值未显示。
我仍在尝试找出我在这里做错了什么。关于我应该去哪里看有什么建议吗?
答案 0 :(得分:2)
更新3:尝试以下轻松访问的代码:
add_action( 'woocommerce_checkout_before_customer_details', 'custom_checkout_fields_before_billing_details', 20 );
function custom_checkout_fields_before_billing_details(){
$domain = 'woocommerce';
$checkout = WC()->checkout;
echo '<div id="my_custom_checkout_field">';
echo '<h3>' . __('My New Fields Section') . '</h3>';
woocommerce_form_field( '_my_field_name', array(
'type' => 'text',
'label' => __('My 1st new field', $domain ),
'placeholder' => __('Please fill in "my 1st new field"', $domain ),
'class' => array('my-field-class form-row-wide'),
'required' => true, // or false
), $checkout->get_value( '_my_field_name' ));
echo '</div>';
}
// Custom checkout fields validation
add_action( 'woocommerce_checkout_process', 'custom_checkout_field_process' );
function custom_checkout_field_process() {
if ( isset($_POST['_my_field_name']) && empty($_POST['_my_field_name']) )
wc_add_notice( __( 'Please fill in "My 1st new field".' ), 'error' );
}
// Save custom checkout fields the data to the order
add_action( 'woocommerce_checkout_create_order', 'custom_checkout_field_update_meta', 10, 2 );
function custom_checkout_field_update_meta( $order, $data ){
if( isset($_POST['_my_field_name']) && ! empty($_POST['_my_field_name']) )
$order->update_meta_data( '_my_field_name', sanitize_text_field( $_POST['_my_field_name'] ) );
}
// Display the extra data in the order admin panel
add_action( 'woocommerce_admin_order_data_after_order_details', 'display_order_data_in_admin', 10, 1 );
function display_order_data_in_admin( $order ){
if( $value = $order->get_meta( '_my_field_name' ) ) {
echo '<div class="order_data_column">
<h4>' . __( "Extra Details", "woocommerce" ) . '</h4>
<p><strong>' . __( 'Some field', "woocommerce" ) . ':</strong> ' . $value . '</p>
</div>';
}
}
代码进入您的活动子主题(活动主题)的function.php文件中。经过测试,可以正常工作。