【问题标题】:WordPress custom REST API endpoint not returning the dataWordPress 自定义 REST API 端点不返回数据
【发布时间】:2019-10-09 09:32:35
【问题描述】:

我正在使用以下代码注册自定义 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】:

    请检查 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

    经过测试并且运行良好。

    【讨论】:

      【解决方案2】:

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

      <?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 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-23
        • 2019-04-07
        • 2018-05-14
        • 2017-04-02
        • 2021-04-05
        • 2021-03-24
        • 2020-09-01
        • 2014-05-06
        相关资源
        最近更新 更多