使用file_get_contents访问WordPress自定义端点时遭遇401未授权错误
解决思路
添加请求头,模拟浏览器访问
很多WordPress安全插件或服务器防火墙会拦截无浏览器标识的请求。你可以为file_get_contents添加请求上下文,带上标准的User-Agent头:$opts = array( 'http' => array( 'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\r\n" ) ); $context = stream_context_create($opts); $response = file_get_contents($api_url, false, $context);改用cURL替代file_get_contents
cURL比file_get_contents更灵活,能更好处理HTTP请求细节,也更容易绕过服务器限制:$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"); $response = curl_exec($ch); curl_close($ch);检查并修复URL合法性
从错误日志可见请求URL多了一个h(hhttp://),可能是构造时的笔误。同时要对$property_slug做URL编码,避免特殊字符破坏URL结构:$api_url = 'http://my-site-here.com/wp-json/xyz/v1/property/' . urlencode($property_slug);排查WordPress安全插件或主题的拦截
暂时禁用所有安全类插件(如Wordfence、iThemes Security),测试请求是否恢复正常。如果正常,需在插件中配置允许外部请求访问你的API端点,或把请求来源的服务器IP加入白名单。验证REST API权限回调是否被覆盖
虽然你设置了permission_callback => '__return_true',但可能有其他插件或主题通过rest_authentication_errors钩子修改了权限逻辑。可以在端点注册代码中添加高优先级钩子,确保权限验证生效:add_filter('rest_authentication_errors', function($error) { if (strpos($_SERVER['REQUEST_URI'], '/wp-json/xyz/v1/property/') !== false) { return null; // 跳过当前端点的权限验证 } return $error; }, 999);
内容的提问来源于stack exchange,提问作者rctneil
相关产品推荐
相关产品推荐

