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

WordPress代码片段失效求助:限制特定用户名与设备访问站点

代码修复方案

原代码存在的问题

  • 仅在首页生效,无法限制全站访问;
  • str_contains 是PHP 8.0+专属函数,若服务器PHP版本低于8.0会直接失效;
  • 判断逻辑大小写敏感,比如用户代理含iOS、用户名是MAC时会匹配失败;
  • 使用JS跳转,用户可通过禁用浏览器JS绕过限制;
  • 未判断用户是否登录,未登录用户会被错误拦截;

修复后的代码

<?php
// 仅针对已登录用户生效
if (is_user_logged_in()) {
    // 获取用户代理并转为小写,统一判断规则
    $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $current_user = wp_get_current_user();
    $username = strtolower($current_user->user_login);

    // 判断设备类型:是否为苹果设备(Mac/iOS)
    $is_apple_device = strpos($user_agent, 'mac') !== false || strpos($user_agent, 'iphone') !== false || strpos($user_agent, 'ipad') !== false;
    // 判断用户名是否含标识
    $username_has_ios = strpos($username, 'ios') !== false;
    $username_has_mac = strpos($username, 'mac') !== false;

    // 定义允许访问的规则
    $allow_access = false;
    // 情况1:苹果设备 + 用户名含ios/mac标识
    if ($is_apple_device && ($username_has_ios || $username_has_mac)) {
        $allow_access = true;
    }
    // 情况2:非苹果设备 + 用户名不含任何苹果标识
    elseif (!$is_apple_device && !$username_has_ios && !$username_has_mac) {
        $allow_access = true;
    }

    // 不允许访问则直接跳转(用PHP header避免JS绕过)
    if (!$allow_access) {
        // 确保输出前执行跳转,避免报错
        wp_redirect(home_url()); // 跳转到站点首页,可自行修改目标地址
        exit;
    }
}
?>

关键修复说明

  • 移除is_front_page()限制,改为针对全站已登录用户生效;
  • 用strpos替代str_contains,兼容所有PHP版本,同时转为统一小写避免大小写匹配问题;
  • 完善苹果设备判断,加入iPhone/iPad的识别;
  • 使用PHP原生wp_redirect跳转,配合exit终止脚本执行,避免用户绕过;
  • 增加is_user_logged_in()判断,只拦截已登录用户,不影响未登录访客;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:07:15