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

如何避免WordPress用户权限判断代码中重复输出相同HTML行

解决方案

你代码里重复输出的HTML逻辑可以通过合并判断条件来简化,完全不需要重复写相同的HTML片段。
原代码中触发这段HTML输出的逻辑可以提炼为:

  • 外层条件:用户已登录 + 当前用户ID不等于文章作者ID,这部分保持不变
  • 内层判断满足以下任意一种情况即可输出HTML:
    • 当前用户角色不是customer
    • 当前用户角色是customer,且当前用户ID等于$authorid

优化后代码

<?php
if (is_user_logged_in() && get_current_user_id() != get_the_author_meta('ID')) {
    // 合并内层判断条件,满足任意一个生效条件就输出HTML
    if (
        !in_array('customer', (array) $user->roles)
        || (in_array('customer', (array) $user->roles) && get_current_user_id() == $authorid)
    ) {
?>
    <i class="fa fa-comments send_designer_msg" designer_id="<?php echo get_the_author_meta("ID"); ?>" logo_number="<?php echo $entryno; ?>" aria-hidden="true"></i>
<?php
    }
}
?>

额外可读性优化

如果想进一步简化判断逻辑,还可以把角色判断提前抽取成变量,后续维护更方便:

<?php
if (is_user_logged_in() && get_current_user_id() != get_the_author_meta('ID')) {
    $is_customer = in_array('customer', (array) $user->roles);
    if (!$is_customer || ($is_customer && get_current_user_id() == $authorid)) {
?>
    <i class="fa fa-comments send_designer_msg" designer_id="<?php echo get_the_author_meta("ID"); ?>" logo_number="<?php echo $entryno; ?>" aria-hidden="true"></i>
<?php
    }
}
?>

修改后HTML片段仅需要写一次,后续调整标签属性、样式只需要修改一处即可,完全避免了重复维护的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:54:04