get_post_meta在调用时不显示自定义字段的值

时间:2015-12-11 03:37:24

标签: wordpress woocommerce

我有以下代码在woocommerce结帐中添加自定义订单字段:

function delivery_time_slots_array () {
return array(
    '' => _('Choose a time slot'),
    '5pm - 6pm' => __('5pm - 6pm', 'woocommerce'),
    '6pm - 7pm' => __('6pm - 7pm', 'woocommerce'),
    '7pm - 8pm' => __('7pm - 8pm', 'woocommerce'),
    '8pm - 9pm' => __('8pm - 9pm', 'woocommerce')
   );
}

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
$fields['order']['order_delivery_time'] = array(
    'type'      => 'select',
    'label'     => __('Delivery time (choose an hour slot between 5pm & 9pm)', 'woocommerce'),
    'class'     => array('form-row-wide'),
    'required'  => true,
    'options'   => delivery_time_slots_array()
    );

然后,接下来是以下代码,用字段值更新订单元数据:

add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta', 10, 2 );

function custom_checkout_field_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['order_delivery_time'] ) ) {
    update_post_meta( $order_id, 'Delivery time', sanitize_text_field($_POST['order_delivery_time']) );
    }
}

这一切都正确显示并返回woocommerce的Orders部分中的值。但是,我无法访问此数据以在感谢页面上返回/显示它。我目前正在使用以下代码:

<li class="delivery_slot">
            <?php _e( 'Delivery Slot', 'woocommerce' ); ?>
            <strong><?php
                $delivery_slots = delivery_time_slots_array();
                $delivery_slot  = get_post_meta($order_id, 'Delivery time', true);
                if( isset($delivery_slots[$delivery_slot]) )
                    echo $delivery_slots[$delivery_slot]; 
            ?></strong>

我在这里查看了2小时的帖子和&amp;在Google上包括以下示例(我的代码镜像),但无法显示值:

How to get the value instead of order_id with get_post_meta()

1 个答案:

答案 0 :(得分:0)

如果您将其附加到order-details.php模板中的任何挂钩,则$order对象将在您的回调函数中可用

function so_34215698_display_order_meta( $order ){
   $delivery_slots = delivery_time_slots_array()
   $delivery_slot  = get_post_meta($order->id, 'Delivery time', true);
        if( isset($delivery_slots[$delivery_slot]) )
             echo $delivery_slots[$delivery_slot]; 
}
add_action( 'woocommerce_order_details_after_order_table', 'so_34215698_display_order_meta' );