自定义 Woocommerce 结帐字段在管理区域中不显示任何值

Custom Woocommerce checkout field doesn't display any value in admin area

在下面的代码中,我在结账订单页面显示了一个自定义字段。

add_action('woocommerce_after_order_notes', 'custom_checkout_placeholder');
function custom_checkout_placeholder($checkout)
{
    echo '<div id="customise_checkout_field">';
    woocommerce_form_field('customised_field', array(
        'type' => 'select',
        'class' => array(
            'my-field-class form-row-wide'
        ) ,
        'label' => __('Rate our support') ,
        'placeholder' => __('') ,
         'options'   => array( __('Bad'),  __('Good'),  __('Very Good')),
    ) , $checkout->get_value('customised_field'));
    echo '</div>';
}

现在我想在管理区显示这个字段。

下面的代码无法正常工作。在管理员中显示标签 'Rate our support' 但不显示用户的答案:

add_action( 'woocommerce_admin_order_data_after_shipping_address', 'checkout_field_admin_order', 10, 1 );

    function checkout_field_admin_order( $order ){
    $customised_field = get_post_meta( $order->get_id(), 'customised_field', true );
        echo '<p>'.__('Rate our support', 'woocommerce').': ' . $customised_field . '</p>';
}

知道为什么管理区域中的这段代码不起作用吗?

缺少的部分是:

add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta' );
function custom_checkout_field_update_order_meta( $order_id ) {
    if ( ! isset( $_POST['customised_field'] ) ) return;
    if ( empty( $_POST['customised_field'] ) ) return;

    update_post_meta( $order_id, '_customised_field', sanitize_text_field( $_POST['customised_field'] ) );
}

在你的最后一个函数中你将拥有:

add_action( 'woocommerce_admin_order_data_after_shipping_address', 'checkout_field_admin_order', 10, 1 );

function checkout_field_admin_order( $order ){
$customised_field = get_post_meta( $order->get_id(), '_customised_field', true );
    echo '<p>'.__('Rate our support', 'woocommerce').': ' . $customised_field . '</p>';
}

更新:同时将您的第一个函数更改为:

add_action('woocommerce_after_order_notes', 'custom_checkout_placeholder');
function custom_checkout_placeholder($checkout)
{
    echo '<div id="customise_checkout_field">';
    woocommerce_form_field('customised_field', array(
        'type' => 'select',
        'class' => array(
            'my-field-class form-row-wide'
        ) ,
        'label' => __('Rate our support') ,
        'placeholder' => __('') ,
        'options'   => array( 
             __('Bad')       => __('Bad'), 
             __('Good')      => __('Good'), 
             __('Very Good') => __('Very Good')
         ),
    ) , $checkout->get_value('customised_field'));
    echo '</div>';
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。