Display value from ACF field in Woocommerce order

2019-07-26 14:42发布

问题:

I´m trying to display a value for delivery date in the emails that Woocommerce automatic sends to the customer when the order is being processed.

I have created a Advanced custom field value called 'leveranstid' and I want it to be shown with every product in the email. I´ve tried to add the code below to the functions.php but it doesn´t seem to work. Nothing shows. I would be very grateful if someone please help me find what´s wrong?

add_action( 'woocommerce_order_item_meta_start', 
'ts_order_item_meta_start', 10, 4 );
function ts_order_item_meta_start( $item_id, $item, $order, $plain_text 
) {

$leverans = get_field(’leveranstid’, $post_id);
echo $leverans;
}

回答1:

The variable $post_id is not defined in $leverans = get_field('leveranstid', $post_id);. Instead try:

add_action( 'woocommerce_order_item_meta_start', 'display', 10, 4 );
function ts_order_item_meta_start( $item_id, $item, $order, $plain_text ) {

    if( $leverans = get_field( 'leveranstid', $item->get_product_id() ) ;
        echo $leverans;
}

It should work if 'leveranstid' ACF field is defined for your products.

For reference see: Get Order items and WC_Order_Item_Product in Woocommerce 3



回答2:

add_action( 'woocommerce_order_item_meta_start', 'ts_order_item_meta_start', 10, 4 );

function ts_order_item_meta_start( $item_id, $item, $order, $plain_text ) {
    if( $leverans = get_field( 'leveranstid', $item->get_product_id() )) {
      echo '<p>'.$leverans.'</p>';
    }
}