Search code examples
phpwordpresswoocommerceadvanced-custom-fieldsemail-notifications

Advanced Custom Fields in WooCommerce Email templates


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


Solution

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

    <?php
        $tracking_num = get_field('tracking-no', $order->get_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 ){
        $tracking_num = get_field('tracking-no', $order->get_id() );
    
        if( $tracking_num ){
            echo '<p>' . $tracking_num . '</p>';
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin).

    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'