如何判断当前登录用户为文章作者并在前端显示对应编辑按钮
问题原因
Undefined variable $user_session_id报错:代码未获取当前登录用户的ID并赋值给该变量,变量为空无定义Undefined variable $author_id报错:代码未获取当前访问的自定义文章(用户资料页)的作者ID并赋值给该变量,变量为空无定义
两个变量均为未定义状态时,PHP判断逻辑会默认二者相等,因此条件永远成立,所有资料页都会显示编辑按钮。
修复代码(WordPress 环境适用)
针对你现有的实现逻辑,替换原有代码即可解决问题:
<?php // 获取当前登录用户ID,未登录时返回0 $current_logged_user_id = get_current_user_id(); // 获取当前被访问文章的作者ID $current_post_author_id = get_post_field( 'post_author', get_the_ID() ); if ( $current_logged_user_id && $current_logged_user_id === $current_post_author_id ) : ?> <style type="text/css"> #profile_edit_button { display: flex !important; } </style> <?php endif; ?>
优化建议
你当前用CSS控制按钮显隐的方案存在安全隐患:默认隐藏的按钮依然存在于页面源码中,访客可以手动修改浏览器CSS强制调出按钮,存在越权风险。更合理的方案是仅当身份匹配时才输出按钮,无需提前写隐藏的按钮和CSS:
<?php $current_logged_user_id = get_current_user_id(); $current_post_author_id = get_post_field( 'post_author', get_the_ID() ); if ( $current_logged_user_id && $current_logged_user_id === $current_post_author_id ) : ?> <button id="profile_edit_button">编辑个人资料</button> <?php endif; ?>
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

