猿问

“伍商务电子邮件”模板中的 ACF 自定义字段

我想在订单完整电子邮件中的产品中显示自定义ACF字段,我有这个钩子,它非常适合非变量产品:


add_filter( 'woocommerce_order_item_name', 'custom_order_item_name', 10, 2 );

function custom_order_item_name( $item_name, $item ) {

  // Targeting email notifications only

  if( is_wc_endpoint_url() )

      return $item_name;


  // Get the WC_Product object (from order item)

  $product = $item->get_product();

  if( $date = get_field('date', $product->get_id()) ) {

    $item_name .= '<br /><strong>' . __( 'Date', 'woocommerce' ) . ': </strong>' . $date;

  }

  if( $location = get_field('location', $product->get_id()) ) {

    $item_name .= '<br /><strong>' . __( 'Location', 'woocommerce' ) . ': </strong>' . $location;

  }

  return $item_name;

}

但是,虽然它对电子邮件中的简单产品显示我的自定义字段(日期和位置)很好,但对于可变产品却没有。


我似乎不明白为什么?


翻过高山走不出你
浏览 100回答 1
1回答

江户川乱折腾

我找到了解决方案。当它是简单产品时,产品 ID 是发布 ID。但是,当它是可变产品时,它们将使用可变产品 ID,而不是发布 ID。这意味着 ACF 字段不会查看产品的帖子 ID,因此不会显示。要为可变产品修复此问题,您必须从数组中获取父 ID:&nbsp;$parent_id=$product->get_parent_id();&nbsp; // If it is a variable product, get the parent ID&nbsp; if($parent_id){&nbsp; &nbsp; $product_id = $parent_id;&nbsp; // else, it is a simple product, get the product ID&nbsp; }else{&nbsp; &nbsp; $product_id = $product->get_id();&nbsp; }完整代码为:// Display Items Shipping ACF custom field value in email notificationadd_filter( 'woocommerce_order_item_name', 'custom_order_item_name', 10, 2 );function custom_order_item_name( $item_name, $item ) {&nbsp; // Targeting email notifications only&nbsp; if( is_wc_endpoint_url() )&nbsp; &nbsp; &nbsp; return $item_name;&nbsp; // Get the WC_Product object (from order item)&nbsp; $product = $item->get_product();&nbsp;$parent_id=$product->get_parent_id();&nbsp; // If it is a variable product, get the parent ID&nbsp; if($parent_id){&nbsp; &nbsp; $product_id = $parent_id;&nbsp; // else, it is a simple product, get the product ID&nbsp; }else{&nbsp; &nbsp; $product_id = $product->get_id();&nbsp; }&nbsp; if( $date = get_field('date', $product_id) ) {&nbsp; &nbsp; $item_name .= '<br /><strong>' . __( 'Date', 'woocommerce' ) . ': </strong>' . $date;&nbsp; }&nbsp; if( $location = get_field('location', $product_id) ) {&nbsp; &nbsp; $item_name .= '<br /><strong>' . __( 'Location', 'woocommerce' ) . ': </strong>' . $location;&nbsp; }&nbsp; return $item_name;}
随时随地看视频慕课网APP
我要回答