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

WordPress中用户名与自定义字段对比实现页面提示功能问询

解决方案:根据登录用户与自定义字段值显示对应提示

看起来你已经搭好了基础代码框架,只差补上用户名获取和判断逻辑啦。我帮你完善了代码,还加了更严谨的逻辑处理:

global $wp_query;
// 获取当前文章ID
$postid = $wp_query->post->ID;
// 获取自定义字段clientName的取值
$getClient = get_post_meta($postid, 'clientName', true);
// 获取当前登录用户的信息
$current_user = wp_get_current_user();

// 先判断用户是否已登录,避免未登录时出现错误
if (is_user_logged_in()) {
    $current_username = $current_user->user_login;
    // 严格对比用户名与自定义字段值
    if ($current_username === $getClient) {
        echo 'this page is assigned for you';
    } else {
        echo 'this page is NOT assigned for you';
    }
} else {
    // 用户未登录时的提示,可按需修改
    echo 'Please log in to view this information';
}

补充说明:

  • 你之前的代码里$c...应该是没写完的当前用户名变量,这里用$current_user->user_login来准确获取登录用户的用户名
  • 加入is_user_logged_in()判断,避免未登录状态下调用用户信息导致的报错
  • 用严格相等符===做对比,确保用户名和自定义字段值的匹配更精准

如果这段代码是在文章循环外部使用,$wp_query->post->ID可能无法正确获取文章ID,这时候可以改用get_the_ID()来替代,调整后的代码如下:

// 循环外获取当前文章ID的方式
$postid = get_the_ID();
$getClient = get_post_meta($postid, 'clientName', true);
$current_user = wp_get_current_user();

if (is_user_logged_in()) {
    $current_username = $current_user->user_login;
    if ($current_username === $getClient) {
        echo 'this page is assigned for you';
    } else {
        echo 'this page is NOT assigned for you';
    }
} else {
    echo 'Please log in to view this information';
}

这样不管是在循环内还是循环外,代码都能稳定运行啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:01:13