问题描述
有什么方法可以添加我创建的一些产品自定义字段,以包括在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_Data
对象上使用get_meta()
方法WC_Product
从其对象中获取自定义字段值他们的)元密钥…