将产品自定义字段添加到 WooCommerce 完成的订单电子邮件

Adding Product Custom Fields to WooCommerce Completed Order Emails

有什么方法可以添加我创建的一些产品自定义字段以包含在 WooCommerce 已完成订单电子邮件中。

我创建了如下自定义字段:

并且我在主题的 functions.php 文件中添加了一些代码,以显示这些自定义字段值,如下所示:

add_action( 'woocommerce_email_after_order_table', 'add_content_on_specific_email', 20, 4 );
  
function add_content_on_specific_email( $order, $sent_to_admin, $plain_text, $email )
{
   if ( $email->id == 'customer_completed_order' ) {
      echo '<h3>Informasi Pengambilan Barang</h3><p class="email-upsell-p">Terima Kasih telah mengkonfirmasi pembayaran Anda, Silahkan tunjukan email ini pada saat pengambilan barang dan berikut informasi dan alamat pengambilan barang:</p>';
      echo '<ul><li>Alamat Pengambilan:</strong> ' . get_post_meta( $product_id, 'kontak_pemberi', true) . '</li>
      <li>No. Telepon :</strong> ' . get_post_meta( $product_id, 'no_hp_pemberi', true) . '</li>
      <li>Nama Pemberi Barang :</strong> ' . get_post_meta( $product_id, 'nama_pemberi', true) . '</li>
      </ul>';
   }
}

但我从来没有得到那些自定义字段值。我做错了什么?

要从订单中获取产品自定义字段,您需要先循环遍历订单项目,然后您才能访问和显示一些产品自定义字段,如下所示:

add_action( 'woocommerce_email_after_order_table', 'add_custom_field_on_completed_order_email', 20, 4 );
function add_custom_field_on_completed_order_email( $order, $sent_to_admin, $plain_text, $email ) {

    if ( 'customer_completed_order' === $email->id ) :

    echo '<h3>' . __("Informasi Pengambilan Barang") . '</h3>
    <p class="email-upsell-p">' . __("Terima Kasih telah mengkonfirmasi pembayaran Anda, Silahkan tunjukan email ini pada saat pengambilan barang dan berikut informasi dan alamat pengambilan barang:") . '</p>';

    // Loop through order items
    foreach ( $order->get_items() as $item ) :

    // Get the main WC_Product Object
    $product = $item->get_variation_id() > 0 ? wc_get_product( $item->get_product_id() ) : $item->get_product();
    
    // Get product custom field values
    $kontak_pemberi = $product->get_meta('kontak_pemberi');
    $no_hp_pemberi  = $product->get_meta('no_hp_pemberi');
    $nama_pemberi   = $product->get_meta('nama_pemberi');
    
    if( ! empty($kontak_pemberi) || ! empty($no_hp_pemberi) || ! empty($nama_pemberi) ) :

    echo '<ul class="item ' . esc_html( $item->get_name() ) . '" style="list-style:none; margin:0 0 3em;">';
    
    if( ! empty($kontak_pemberi) )
        echo '<li>' . __("Alamat Pengambilan:") . '</strong> ' . $kontak_pemberi . '</li>';
    
    if( ! empty($no_hp_pemberi) )
        echo '<li>' . __("No. Telepon :") . '</strong> ' . $no_hp_pemberi . '</li>';
        
    if( ! empty($nama_pemberi) )
        echo '<li>' . __("Nama Pemberi Barang :") . '</strong> ' . $nama_pemberi . '</li>';
        
    echo '</ul>';
    
    endif;
    endforeach;
    endif;
}

代码进入活动子主题(或活动主题)的 functions.php 文件。它应该有效。

注意: 自 WooCommerce 3 起,您可以在 WC_Product 对象上使用 WC_Data 方法 get_meta() 来获取自定义字段值( s) 来自它的(他们的)元键…