WordPress使用wp_remote_post更新主题根目录JSON文件失败求助
问题排查与解决方案
核心误区
你当前的用法逻辑完全不成立:wp_remote_post() 是 WordPress 封装的 HTTP 客户端工具,作用是向指定 URL 发起 POST 请求。直接向静态 species.json 文件的 URL 发请求时,服务器默认只会返回文件内容,不会处理任何写入逻辑,所以文件不会更新。
排查步骤
先打印请求返回结果确认错误:在现有代码中把 wp_remote_post( $url, $args ); 替换为以下代码,运行后即可看到服务器的响应状态,大概率是405方法不允许,或是直接返回原有JSON内容:
$response = wp_remote_post( $url, $args ); echo '<pre>'; var_dump($response); echo '</pre>';
保留wp_remote_post的可行方案
你要保留 wp_remote_post 写法的话,需要新增一个后端处理接口接收请求、执行写入操作,不能直接请求静态JSON文件,操作步骤如下:
- 首先在主题根目录新建
save_specie.php处理文件,写入以下内容:
<?php // 加载WordPress核心 require_once dirname(__FILE__, 3) . '/wp-load.php'; // 权限校验,避免恶意调用 if (!current_user_can('manage_options')) { wp_die('无操作权限'); } // 接收JSON参数 $input = file_get_contents('php://input'); $new_item = json_decode($input, true); if (empty($new_item['specie']) || empty($new_item['rate'])) { wp_die('参数不完整'); } // 读取原有JSON内容 $json_path = get_template_directory() . '/species.json'; $existing_data = json_decode(file_get_contents($json_path), true) ?: []; // 追加新数据 $existing_data[] = $new_item; // 写回文件 file_put_contents($json_path, json_encode($existing_data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); wp_send_json_success('写入完成');
- 修改
front-page.php中的请求URL,替换为处理接口的地址:
// 把原来的 $url = get_template_directory_uri() . '/species.json'; 替换为下面的代码 $url = get_template_directory_uri() . '/save_specie.php';
额外注意事项
- 你当前的
species.json末尾多了一个无效逗号,会导致JSON解码失败,需要先删掉第二个对象后面的逗号 - 确保
species.json文件有服务器写入权限,通常权限设为644、文件所有者为服务器运行用户(如www-data)即可 - 不存在不用文件操作函数直接修改服务器静态文件的方案,
wp_remote_post和file_put_contents是不同环节的工具,二者没有替代关系,写入本地文件必然要用到文件操作函数
内容的提问来源于stack exchange,提问作者Raging Vids
相关产品推荐
相关产品推荐

