I'm trying to display a custom field on an email.
Here's the script that I thought should work:
<?php if ($day) : ?>
<p><strong><?php _e('day:', 'woocommerce-pip'); ?></strong> <?php echo $order->day; ?></p>
<?php endif; ?>
But it doesn't work. The name of the field is 'day'
.
Should this work? What am I missing?
Thanks.
I assume that you have already set correctly this custom field on checkout page with some code that displays the custom field and save the value of this custom field within the order in database (if not, you will get nothing).
You need first to retrieve the order ID
before trying to get the value of this custom field and there can be 2 cases:
$order
variable or object. You simply retrieve it with:$order_id = $order->id;
// or
$order_id = str_replace( '#', '', $order->get_order_number() );
$order
object, you will need to get it first:global $woocommerce, $post;
$order = new WC_Order( $post->id );
// and after you can get the order ID
$order_id = $order->id;
// or
$order_id = str_replace( '#', '', $order->get_order_number() );
Now you can get the value and display it because you have $order_id
:
<?php $day = get_post_meta( $order_id, 'day', true );
if ( !empty( $day ) ) : ?>
<p><strong><?php _e('day:', 'woocommerce-pip'); ?></strong> <?php echo $day; ?></p>
<?php endif; ?>
But you should check in your database within the order_id
as post_id
in wp_postmeta
table, that a meta_value => 'day'
exist with some value in the corresponding meta_value
row/column. If not, there is certainly a problem with your code when you create this custom field and save the value on checkout page.