问题描述
在 woocommerce 订单电子邮件中,我想自定义字段与帐单地址一起添加。这是我尝试过的。但它给出了错误。
add_filter('woocommerce_order_formatted_billing_address',array($this,'woo_custom_order_formatted_billing_address'),10,2);
function woo_custom_order_formatted_billing_address( $address,$WC_Order ) {
$address = array(
'first_name' => $WC_Order->billing_first_name . ' ' . $WC_Order->billing_last_name,'company' => $WC_Order->billing_company,'address_1' => $WC_Order->billing_address_1,'address_2' => $WC_Order->billing_address_2,'city' => $WC_Order->billing_city,'state' => $WC_Order->billing_state,'area' => $WC_Order->billing_area,'emirates' => $WC_Order->billing_emirates,'nearest_landmark' => $WC_Order->billing_nearest_landmark,'country' => $WC_Order->billing_country,'email' => $WC_Order->billing_email,'phone' => $WC_Order->billing_phone,);
return $address;
}
任何人请帮忙。
解决方法
您可以使用 woocommerce_order_get_formatted_billing_address
过滤器代替 woocommerce_order_formatted_billing_address
来确保更改帐单邮寄地址的最终结果。
对于 billing_area
、billing_emirates
和 billing_nearest_landmark
自定义字段,您需要获取它们各自的值作为订单 postmeta。
字段的排序也将应用于显示 后端和前端中的帐单邮寄地址。
帐单电话和帐单电子邮件字段添加在
/woocommerce/emails/email-addresses.php
电子邮件中的帐单邮寄地址
模板。所以没有必要添加它们,否则它们会显示双倍。
以下代码应该可以工作。
add_filter( 'woocommerce_order_get_formatted_billing_address','add_custom_field_billing_address',10,3 );
function add_custom_field_billing_address( $address,$raw_address,$order ) {
$countries = new WC_Countries();
// gets country and state codes
$billing_country = $order->get_billing_country();
$billing_state = $order->get_billing_state();
// gets the full names of the country and state
$full_country = ( isset( $countries->countries[ $billing_country ] ) ) ? $countries->countries[ $billing_country ] : $billing_country;
$full_state = ( $billing_country && $billing_state && isset( $countries->states[ $billing_country ][ $billing_state ] ) ) ? $countries->states[ $billing_country ][ $billing_state ] : $billing_state;
$data = array(
$order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),$order->get_billing_company(),$order->get_billing_address_1(),$order->get_billing_address_2(),$order->get_billing_city(),$full_state,$order->get_meta( '_billing_area',true ),// or $order->get_meta( 'billing_area',true )
$order->get_meta( '_billing_emirates',// or $order->get_meta( 'billing_emirates',true )
$order->get_meta( '_billing_nearest_landmark',// or $order->get_meta( 'billing_nearest_landmark',true )
$full_country,);
// removes empty fields from the array
$data = array_filter( $data );
// create the billing address using the "<br/>" element as a separator
$address = implode( '<br/>',$data );
return $address;
}
代码已经过测试并且可以正常工作。