WordPress用户元数据数组仅显示首个值的技术求助
问题说明
我通过WP-Webhook插件,利用Webhook将通话详情添加到对应用户的元数据中。由于数据会持续添加,存储的是数组格式,但前端仅显示第一个值。我尝试了两种方法都无法显示全部数据,同时使用了PHP Code Snippets插件(不确定是否与此问题相关)。
用户元数据中的输出格式:
// 存储的元数据数组 array ( 0 => 'phone_data 1', 1 => 'phone data 2', 2 => 'phone data 3', 3 => 'phone data 4', 4 => 'phone data 5', 5 => 'phone data 6', )
我尝试的代码:
// 第一种尝试 $current_user = wp_get_current_user(); if ( $current_user ) { $meta = get_user_meta( $current_user->ID, 'phone_calls' , true ); if ( ! is_array( $meta ) ) { $meta = array(); } echo 'User phone calls: ' . $current_user->phone_calls . ; } // 第二种尝试 $current_user = wp_get_current_user(); echo 'User phone calls: ' . $current_user->phone_calls . ;
问题原因
- 直接调用
$current_user->phone_calls无效,WordPress不会自动将用户元数据挂载到WP_User对象属性上,必须通过get_user_meta()获取。 - 数组直接和字符串拼接时,PHP会将数组转为
Array字符串或仅显示第一个元素,无法完整输出所有内容。 - 代码末尾的
. ;属于语法错误,会导致PHP运行报错。
正确实现代码
要完整显示所有通话记录,需先获取数组再遍历输出:
$current_user = wp_get_current_user(); if ($current_user->ID) { // 确保用户已登录 // 获取用户元数据,第三个参数true返回单个值(此处数组为单个值),可根据实际存储调整 $phone_calls = get_user_meta($current_user->ID, 'phone_calls', true); // 确保变量为数组,避免空值或非数组情况 if (!is_array($phone_calls)) { $phone_calls = []; } echo '用户通话记录:<br>'; // 遍历数组输出每条记录,用esc_html防止XSS注入 foreach ($phone_calls as $call) { echo '- ' . esc_html($call) . '<br>'; } }
补充说明
- 若
get_user_meta第三个参数设为false,返回的是二维数组(格式为array(0 => array(...))),需先提取内层数组再遍历:$phone_calls = get_user_meta($current_user->ID, 'phone_calls', false); $phone_calls = !empty($phone_calls) ? $phone_calls[0] : []; - PHP Code Snippets插件本身不影响功能,只要代码语法正确、逻辑无误即可正常运行。
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

