Advanced Custom Fields in WooCommerce Email templates

久未见 提交于 2020-02-27 13:46:58

问题


I am using Advanced Custom Fields (ACF) plugin in WooCommerce and I have set a custom field named "tracking-no".

How can I display the value of this custom field in the Woocommerce template emails/customer-completed-order.php?

I am using this code:

<?php
    if(get_field('tracking-no'))
    {
        echo '<p>' . get_field('tracking-no') . '</p>';
    }
?>

But I doesn't get anything.

Thanks


回答1:


In your WooCommerce template you should get first the order ID as argument in get_field():

<?php
    // Get the $order ID (WooCommerce version compatibility)
    if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
        $order_id = int_val( $order->id ); // Older than 3.0
    } else {
        $order_id = int_val( $order->get_id() ); // 3.0+
    }

    $tracking_num = get_field('tracking-no', $order_id );

    if( $tracking_num ){
        echo '<p>' . $tracking_num . '</p>';
    }
?>

You can also use instead any email notification hook that you can find on this template, this way:

add_action( 'woocommerce_email_order_details', 'my_custom_field_in_completed_notification', 10, 4 );
function my_custom_field_in_completed_notification( $order, $sent_to_admin, $plain_text, $email ){
    // Get the $order ID (WooCommerce version compatibility)
    if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
        $order_id = int_val( $order->id ); // Older than 3.0
    } else {
        $order_id = int_val( $order->get_id() ); // 3.0+
    }

    $tracking_num = get_field('tracking-no', $order_id );
    if( $tracking_num ){
        echo '<p>' . $tracking_num . '</p>';
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

In this case we don't override WooCommerce templates. You can also use that 2 similar hooks:

woocommerce_email_order_meta
woocommerce_email_customer_details


来源:https://stackoverflow.com/questions/44720853/advanced-custom-fields-in-woocommerce-email-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!