1
votes

Trying to get an advanced custom field in a woocommerce product to pass to the new order email for the admin. It's only there for the admin reference and is specific to each product. I have tried and this gets it to the backend but not in the email.

add_action( 'woocommerce_before_order_itemmeta', 'product_size', 10, 3 );
function product_size( $item_id, $item, $product ){
    // Only in backend Edit single Order pages
    if( current_user_can('edit_shop_orders') ):

    // The product ID 
    $product_id = $product->get_id();

    // Get your ACF product value 
    $acf_value = __('Size: ') . get_field( 'package_size', $product_id );

    // Outputing the value of the "package size" for this product item
    echo '<div class="wc-order-item-custom"><strong>'. $acf_value .'</strong></div>';

    endif;
}

I tried using this to get to the email but it killed the order process. It went through in the backend but after hitting place order, it just refreshes the checkout page and does not go to the thank you or generate an email.

add_action( 'woocommerce_email_order_details', 'display', 10, 4 );
function display( $order, $sent_to_admin, $plain_text, $email ) {
global $product;
$id = $product->get_id();
    $value = get_field( "package_size", $id );

    if($value)  {
        echo "<p>Package Size : ".$value ."</p>";
    }

}

Any suggestions or help is appreciated.

1

1 Answers

2
votes

The WC_Product object $product can't be defined as a global variable. You need to use a foreach loop to get order items first.

But as an order can have many items (products) you may get many displays for this ACF field.

Your revisited code:

add_action( 'woocommerce_email_order_details', 'display_package_size_email_order_details', 10, 4 );
function display_package_size_email_order_details( $order, $sent_to_admin, $plain_text, $email ) {
    // Only admin notifications
    if( ! $sent_to_admin )
         return; // Exit

    foreach( $order->get_items() as $item ) {
        if( $package_size = get_field( "package_size", $item->get_product_id() ) ){
            echo '<p><strong>'.__('Package Size').': </strong>'.$package_size.'</p>';
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Related: Display value from ACF field in Woocommerce order email