WordPress自定义REST API端点未返回数据

问题描述 投票:0回答:1

我正在使用以下代码注册自定义WordPress端点:

add_action('rest_api_init', function(){
  register_rest_route('custom', array(
    'methods' => 'GET',
    'callback' => 'return_custom_data',
  ));
});

function return_custom_data(){
  return 'test';
}

但是,这是我向它发送请求时得到的结果:

{'namespace': 'custom', 'routes': {'/custom': {'namespace': 'custom', 'methods': ['GET'], 'endpoints': [{'methods': ['GET'], 'args': {'namespace': {'required': False, 'default': 'custom'}, 'context': {'required': False, 'default': 'view'}}}], '_links': {'self': 'http://localhost/index.php/wp-json/custom'}}}, '_links': {'up': [{'href': 'http://localhost/index.php/wp-json/'}]}}

它确实识别端点,但是未返回我在回调中指定的数据。

有什么建议吗?

谢谢!

wordpress wordpress-rest-api
1个回答
0
投票

请检查wordpress.org中的register_rest_route文档,您可以在该函数中传递四个参数。前两个参数是必需的。

使用以下代码与自定义端点一起使用

add_action( 'rest_api_init', 'custom_endpoints' );
function custom_endpoints() {
  register_rest_route( 'custom', '/v2', array(
        'methods' => 'GET',
        'callback' => 'custom_callback',
    ));
}


function custom_callback() {
    return "custom";
}

端点将为http://localhost/index.php/wp-json/custom/v2

经过测试,效果很好。

© www.soinside.com 2019 - 2024. All rights reserved.