WordPress子主题API调用端点错误问题求助
WordPress子主题API调用端点配置错误解决
问题说明
本地测试的「前端JavaScript+后端PHP调用第三方API」流程运行正常,但迁移到WordPress子主题后出现报错:Error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
推测是子主题functions.php的端点设置错误,当前已将JS的baseURL改为https://purgace.com/wp-content/themes/Divi%20Pledge%20Theme/functions.php,需要正确的端点配置方案。
报错原因
直接请求WordPress主题的functions.php文件时,WordPress会加载完整的主题环境,输出包含<!DOCTYPE>的HTML页面内容,而非纯JSON响应,导致前端尝试解析JSON时失败。
正确配置方案
使用WordPress官方REST API注册自定义端点,这是规范且安全的后端交互方式,具体步骤如下:
1. 修改子主题functions.php代码
移除原有的直接API调用逻辑,改用REST API注册端点:
<?php function my_theme_enqueue_styles() { $parent_style = 'divi-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); // 注册自定义REST API端点 add_action('rest_api_init', function () { register_rest_route( 'pledge/v1', // 自定义命名空间,避免冲突 '/organizations', // 端点路径 array( 'methods' => 'GET', // 允许的请求方法 'callback' => 'get_pledge_organizations', // 处理请求的回调函数 'permission_callback' => '__return_true' // 公开访问权限,可根据需求调整 ) ); }); function get_pledge_organizations() { $url = 'https://api.pledge.to/v1/organizations'; $api_key = '你的实际API密钥'; // 替换为你的Pledge API密钥 // 设置请求头 $context = stream_context_create([ 'http' => [ 'header' => "Authorization: Bearer $api_key\r\n" ] ]); // 请求第三方API $response = file_get_contents($url, false, $context); if ($response === false) { return new WP_Error('fetch_failed', '获取机构数据失败', array('status' => 500)); } // 解析响应并以WordPress REST规范返回 $data = json_decode($response, true); return rest_ensure_response($data); } ?>
2. 修改前端JavaScript代码
更新baseURL为WordPress REST API的端点地址:
// 替换为你的站点域名 const baseURL = 'https://purgace.com/wp-json/pledge/v1'; function getOrgs(){ return fetch(`${baseURL}/organizations`) .then(response => response.json()) .then(data =>{ console.log(data); // 这里添加数据渲染逻辑 }) .catch(error => console.error('Error:', error)); } getOrgs();
3. 验证测试
保存修改后,刷新前端页面,打开浏览器控制台查看输出。若成功获取数据,说明配置生效;若仍有错误,可检查:
- API密钥是否正确
- WordPress REST API是否启用(默认已启用,若有插件限制需调整)
- 第三方API的请求权限是否正常
内容的提问来源于stack exchange,提问作者vroque2022
相关产品推荐
相关产品推荐

