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

替换file_get_contents()为wp_remote_get()后失效报错,如何解决?

问题修复方案

错误原因

file_get_contents() 直接返回文件内容的字符串,但 wp_remote_get() 返回的是一个响应数组(包含状态码、响应头、响应体等信息),直接把数组传给 base64_encode() 自然会触发类型错误。

修复步骤

  1. 先通过 wp_remote_get() 获取完整响应数组
  2. 验证响应是否成功(避免请求失败导致后续报错)
  3. 从响应数组中提取 body 字段(这才是文件内容的字符串),再传入 base64_encode()

修正后的代码

define( 'ICON_PATH', plugins_url( 'img/sh-logo.svg', __FILE__ ) );

// 先获取响应数组
$icon_response = wp_remote_get(ICON_PATH);

// 检查请求是否成功,避免错误
if ( !is_wp_error($icon_response) && wp_remote_retrieve_response_code($icon_response) === 200 ) {
    // 提取响应体字符串
    $icon_content = wp_remote_retrieve_body($icon_response);
    define( 'BASE64_PLUGIN_ICON', base64_encode($icon_content) );
} else {
    // 请求失败时的 fallback 处理,比如设置默认值
    define( 'BASE64_PLUGIN_ICON', '' );
}

另外注意:原代码中 img\sh-logo.svg 的反斜杠建议改成正斜杠 img/sh-logo.svg,因为 plugins_url() 生成的是 URL 路径,正斜杠更符合规范,也避免转义问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 16:39:55