【问题标题】:get_post_meta not showing the value of custom field when calledget_post_meta 调用时不显示自定义字段的值
【发布时间】:2016-03-16 21:41:08
【问题描述】:

我有以下代码在 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>

我在这里和 Google 上查看了 2 小时的帖子,包括以下示例(我的代码反映了该示例),但无法获得要显示的值:

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

【问题讨论】:

  • $delivery_slot 有什么设置吗?

标签: wordpress woocommerce


【解决方案1】:

如果您将它附加到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' );

【讨论】:

  • 谢谢赫尔加!我刚刚将thankyou.php 函数中的$order_id 更改为$order-> id per yours & 它起作用了:)。
猜你喜欢
  • 2017-05-22
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
相关资源
最近更新 更多