0
votes

I've had the following code to add a custom order field in the woocommerce checkout:

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()
    );

Then, followed by the below code to update the order meta with field value:

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']) );
    }
}

This all displays correctly and returns the value within the Orders section of woocommerce. However, I can't then access this data to return/display it on the thank-you page. I'm using the following code at present:

<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>

I've reviewed 2 hours of posts here & on Google including the below example (which my code mirrors), but cannot get the value to display:

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

1
Does $delivery_slot get anything set?Mat Taylor

1 Answers

0
votes

If you attach it to any of the hooks in the order-details.php template then the $order object will be available in your callback function

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