You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress自定义用户Telegram字段数据获取失败问题求助

WordPress single.php中Telegram链接显示为Array的问题修复

问题背景

通过functions.php成功自定义用户资料的联系方式字段(移除默认社交字段,新增phone1和telegram1),但在single.php中获取telegram1字段值时,Telegram按钮链接跳转到https://t.me/Array,电话功能正常。

错误原因

查看PHP代码发现,获取Telegram字段时使用了未定义的$author_id变量:

$telegram_input1 = get_the_author_meta('telegram1', $author_id);

而电话字段使用的是正确的$curauth_id(当前登录用户ID)。未定义的$author_id会被PHP当作空值处理,get_the_author_meta在未传入合法用户ID时会返回数组,最终导致$telegram_username1变成Array,链接显示异常。

修复方案

将Telegram字段的用户ID参数替换为已定义的$curauth_id,同时增加空值判断避免后续错误:

修改后的PHP代码

<?php
$curauth_id = get_current_user_id();

$author_phone1 = get_the_author_meta('phone1', $curauth_id);
$phone_display1 = preg_replace("|\s|","",$author_phone1);

// 替换$author_id为$curauth_id,并增加空值处理
$telegram_input1 = get_the_author_meta('telegram1', $curauth_id);
$telegram_username1 = !empty($telegram_input1) ? str_replace('@', '', $telegram_input1) : '';
?>

验证效果

修改后,Telegram链接会正确获取用户填写的telegram1字段值,自动去掉@符号后生成https://t.me/用户名的有效链接。

额外优化建议

  • 可增加Telegram用户名格式校验,确保仅包含字母、数字、下划线和点
  • 若需获取文章作者的信息而非当前登录用户,应替换get_current_user_id()为get_the_author_meta('ID'),根据业务场景选择正确的用户ID来源

内容的提问来源于stack exchange,提问作者Meng888

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:57:23