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

WordPress自定义REST API通过代码调用返回false问题求助

问题分析与解决方案

问题背景

自定义了WordPress的REST API路由/mmw/v1/testing,浏览器直接访问https://agriculturecoaching.in/wp-json/mmw/v1/testing能正常返回JSON数据,但使用前端fetch调用时返回false。相关代码如下:

前端fetch代码

const userAction = async () => {
        const response = await fetch('https://rajivrajput.com/wp-json/mmw/v1/testing', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        const myJson = await response.json(); //extract JSON from the http response
        console.log(myJson);
        // do something with myJson
        document.getElementById("div").innerHTML = myJson;
    }

WordPress functions.php代码

$user_id = ""; //<- add this

add_action( 'rest_api_init', 'add_custom_users_api');

function add_custom_users_api(){
    $GLOBALS['user_id'] = get_current_user_id(); //<- add this

    // route url: domain.com/wp-json/mmw/v1/testing
    register_rest_route( 'mmw/v1', 'testing', array(
        'methods' => 'GET',
        'callback' => 'get_custom_users_data',
    ));
}
//Customize the callback to your liking
function get_custom_users_data(){
     return $user_info =  get_user_by( 'id', $GLOBALS['user_id'] ); //<- add this
}

核心问题与解决步骤

1. 解决跨域CORS限制

前端请求域名(rajivrajput.com)与API所在域名(agriculturecoaching.in)不一致,浏览器会触发跨域安全限制,导致请求无法正常获取数据。

在functions.php中添加CORS处理代码:

add_action('rest_api_init', function () {
    remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
    add_filter('rest_pre_serve_request', function ($value) {
        // 生产环境建议替换为前端实际域名,比如https://rajivrajput.com,避免通配符带来的安全风险
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type');
        return $value;
    });
}, 15);

2. 传递用户登录凭证

浏览器直接访问时会自动携带登录Cookie,但fetch默认不会发送凭证,导致API无法识别登录用户,get_current_user_id()返回0,最终get_user_by(0)返回false。

修改前端fetch代码,添加凭证传递配置,并修正请求域名与浏览器访问一致:

const userAction = async () => {
        const response = await fetch('https://agriculturecoaching.in/wp-json/mmw/v1/testing', {
            method: 'GET',
            credentials: 'include', // 关键:携带登录Cookie凭证
            headers: {
                'Content-Type': 'application/json'
            }
        });
        const myJson = await response.json();
        console.log(myJson);
        // 对象不能直接插入innerHTML,需转为字符串
        document.getElementById("div").innerHTML = JSON.stringify(myJson);
    }

3. 修复用户ID获取的作用域问题

当前代码在rest_api_init钩子中提前获取user_id并存入全局变量,但该钩子执行上下文与API请求实际处理上下文不一致,容易导致用户ID错误。正确做法是在回调函数中直接获取当前请求的用户ID:

修改functions.php代码:

add_action( 'rest_api_init', 'add_custom_users_api');

function add_custom_users_api(){
    register_rest_route( 'mmw/v1', 'testing', array(
        'methods' => 'GET',
        'callback' => 'get_custom_users_data',
        // 可选:添加权限验证,确保只有登录用户能访问
        'permission_callback' => function() {
            return is_user_logged_in();
        }
    ));
}

function get_custom_users_data(){
    $user_id = get_current_user_id();
    // 处理未登录场景
    if ($user_id === 0) {
        return new WP_Error('not_logged_in', '用户未登录', array('status' => 401));
    }
    return get_user_by( 'id', $user_id );
}

额外注意点

  • 若为子域名跨域,需确保WordPress的Cookie配置中domain参数设置为父域名,保证凭证能正常传递。
  • 未登录状态下API会返回明确的错误信息,可根据业务需求调整权限逻辑或返回内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:42:50