首页 > 解决方案 > 如何在电子邮件中显示 ACF 的字段或字段键?

问题描述

我为 WooCommerce 使用 ACF 插件和 ACF。如果用户 Woocommerce 更改了他的数据,管理员会收到一封有关这些更改的电子邮件。

这是完整的代码:

if( !class_exists('WooCommerceNotifyChanges') ){

class WooCommerceNotifyChanges{

function __construct(){
// customer saves main account data
add_action('woocommerce_save_account_details', array( $this, 'woocommerce_send_notification' ), 15, 1 );

}

function woocommerce_send_notification( $user_id ){
$body       = '';
$to         = 'info@domain.com';    //address that will receive this email
$subject    = 'One of your customers has updated their information.';

$user      = new WP_User( $user_id );
$user_name = $user->user_login;

$body .= '<table>';
$body .= '<tr><td><strong>' . __("Account") . '</strong></td></tr>';
$body .= '<tr><td>Username: </td><td>' . $user_name                                         . '</td></tr>';
$body .= '<tr><td>First name: </td><td>' . $user->billing_first_name . '</td></tr>';
$body .= '<tr><td>Last name: </td><td>' . $user->billing_last_name  . '</td></tr>';
$body .= '<tr><td>Phone: </td><td>' . get_field( 'user_phone', "user_{$user_id}" ) . '</td></tr>';
$body .= '<tr><td>Age: </td><td>' . get_field( 'user_age', "user_{$user_id}" ) . '</td></tr>';
$body .= '</table>';    

//set content type as HTML
$headers = array('Content-Type: text/html; charset=UTF-8;');

//send email
if( wp_mail( $to, $subject, $body, $headers ) ){
    //echo 'email sent';
}else{
    //echo 'email NOT sent';                
}
//exit();
}
}
new WooCommerceNotifyChanges(); 
} 

我创建了几个自定义字段并在用户帐户中显示这些字段。

在给管理员的电子邮件中,这些字段“user_phone”和其他字段未显示。

例如,“ACF for WooCommerce”插件将数据库中的“user_phone”字段保存为 meta_key:“field_5b7e4f388fd11”和 meta_value:“+79998006655”。

在此处输入图像描述

在我的代码中,该字段显示如下:

get_field( 'user_phone', "user_{$user_id}" )

当我把字段键“field_5b7e4f388fd11”而不是字段名...

get_field( 'field_5b7e4f388fd11', "user_{$user_id}" )

我收到一封包含空白字段的电子邮件。

我该如何解决这个问题?


更新:我可以直接使用get_user_meta:

get_user_meta($user_id, 'field_5b7e4f388fd11', $single=true);

此选项有效,但如果我将现有字段值替换为新的“+78009995566”,例如“+79998006655”,则所有内容都正确存储在数据库中,并且旧版本的“+79998006655”进入管理员的电子邮件。

如果自定义字段是复选框,则它已正确存储在数据库中,但管理员电子邮件中仅显示“数组”。

是的,给管理员的电子邮件很长一段时间。

如何补救?

标签: phpmysqlwordpresswoocommerceadvanced-custom-fields

解决方案


无需添加大括号

试试这个代码:

get_field( 'user_age', "user_$user_id" ) 

更新 1:

更多信息在ACF 官方文档

ACF 文档中的示例:

// This example will retrieve a field value from a user with an ID of 1.
$variable = get_field('field_name', 'user_1');

更新 2:

尝试这个:

get_field('user_phone', 'user_' . $user_id )


推荐阅读