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

WordPress自定义API端点必填参数仅传参数名未校验,如何修复?

解决WordPress REST API强制要求参数必须传入有效值的问题

问题根源

当前代码仅设置了required => true,但WordPress REST API的required规则只验证参数是否存在,不检查参数值是否有效。当请求携带?osm_geometry(仅参数名无值)时,参数会被视为存在且值为空字符串,不会触发必填提示,最终导致你的回调函数因参数值为空返回所有滑雪场数据。

解决方案

通过添加参数验证规则,强制检查参数值非空且有效,以下两种方法均可实现:

方法一:自定义验证回调函数

给osm_geometry参数添加validate_callback,直接验证参数值是否非空:

add_action('rest_api_init', function(){
    register_rest_route('fs/v1', '/fs_ski_resort/', array(
        'methods'   => 'GET',
        'callback'  => 'fs_ski_resort_data',
        'args'      =>  array(
            'osm_geometry' => array(
                'required' => true,
                'validate_callback' => function($value) {
                    // 验证参数值非空且不为空白字符
                    return !empty(trim($value));
                },
                'description' => '必须传入有效的OSM几何标识,格式如way-xxxxxx',
                'error_messages' => array(
                    'invalid' => 'osm_geometry必须传入有效值,不能为空',
                )
            )
        ) 
    )
    );
});

方法二:利用类型和长度规则限制

设置参数类型为字符串,并要求最小长度大于0,自动拦截空值:

add_action('rest_api_init', function(){
    register_rest_route('fs/v1', '/fs_ski_resort/', array(
        'methods'   => 'GET',
        'callback'  => 'fs_ski_resort_data',
        'args'      =>  array(
            'osm_geometry' => array(
                'required' => true,
                'type' => 'string',
                'min_length' => 1,
                'description' => '必须传入有效的OSM几何标识,格式如way-xxxxxx',
                'error_messages' => array(
                    'min_length' => 'osm_geometry必须传入有效值,不能为空',
                )
            )
        ) 
    )
    );
});

效果说明

修改后,当请求仅携带?osm_geometry(无值)时,REST API会直接返回你定义的错误提示,不会进入回调函数执行,也就不会返回所有滑雪场数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 05:45:00