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

WordPress custom REST API endpoint not returning the data

我正在使用以下代码注册自定义 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/'}]}}

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

有什么建议吗?

谢谢!

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

使用以下代码来处理自定义端点

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

经过测试并且运行良好。

下面是注册自定义端点的完整代码以及如何调用它。

<?php

add_action( 'rest_api_init', function () {

$namespace = 'custom_apis/v1';

  register_rest_route( $namespace, 'get_helloworld', array(
    'methods' => 'GET',
    'callback' => 'helloworld',
  ) );



  function helloworld(){

      return 'Hello world';
  }

  } );

?>

如何调用您的自定义端点。

http://domain_name/wp-json/custom_apis/v1/get_helloword