Adam
Adam

Reputation: 29

Calling and displaying a WooCommerce custom checkout field value

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.

Upvotes: 0

Views: 1057

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 253886

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:

  1. You have already the $order variable or object. You simply retrieve it with:
$order_id = $order->id;

// or

$order_id = str_replace( '#', '', $order->get_order_number() );
  1. You don't have the $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.

Upvotes: 1

Naveen
Naveen

Reputation: 198

For display custom field like this

<?php echo get_post_meta( get_the_ID(), ‘tes_custom_field’, true ); ?>

for more information check this vary good tutorial http://www.themelocation.com/how-to-display-custom-field-value-on-product-page-in-woocommerce/

Upvotes: 0

Related Questions