Display product ACF value in Woocommerce admin email notifications

徘徊边缘 提交于 2019-12-11 07:57:27

问题


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:


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



来源:https://stackoverflow.com/questions/52952865/display-product-acf-value-in-woocommerce-admin-email-notifications

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