1
votes

In Woocommerce with Advanced Custom Fields plugin, we have added a custom field to products and this field value is specific to each product.

Now I am trying to add this custom field value to our Woocommerce order confirmation emails.

I have tried the following code with no success:

<?php
    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+
    }

    $inst1 = get_field(‘how1’, $order_id );

    if( $inst1 ){
        echo '<p>' . $inst1 . '</p>';
    }
?> with Advanced Custom Fields plugin
1
Welcome to Stack Overflow. You are using a Wordpress function to get a WooCommerce field, and I'm 99% sure that's the problem. You need to use a WooCommerce function or class property to get the custom field. I don't know how the custom field plugin operates, but my guess would be you need to get the properties of the WooCommerce product using the WC_Product class.fred2

1 Answers

0
votes

As your custom field is specific to "product" post type (but NOT to "order" post type) you need to get first the order items to get the product ID that you should use with ACF get_field() function this way:

<?php

    foreach ( $order->get_items() as $item ) {
        // Get the product ID
        if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
            $product_id = $item['product_id']; // Older than 3.0
        } else {
            $product_id = $item->get_product_id(); // 3.0+
        }

        $inst1 = get_field( 'how1', $product_id );

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

<?

The custom field value will be displayed for each item in the order, as an order can have many items in it.


References: