在Woocommerce管理订单页面中显示自定义结帐字段值

问题描述 投票:2回答:1

在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' );?>

出现额外详细信息和某些字段:但不显示自定义字段值。

我还在试图弄清楚我在这里做错了什么。关于我应该看哪里的任何建议?

php wordpress woocommerce backend orders
1个回答
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文件中。经过测试和工作。

© www.soinside.com 2019 - 2024. All rights reserved.