WordPress自定义REST API端点未返回数据
我正在使用以下代码注册自定义WordPress端点:WordPress自定义REST API端点未返回数据,wordpress,wordpress-rest-api,Wordpress,Wordpress Rest Api,我正在使用以下代码注册自定义WordPress端点: add_action('rest_api_init', function(){ register_rest_route('custom', array( 'methods' => 'GET', 'callback' => 'return_custom_data', )); }); function return_custom_data(){ return 'test'; } 但是,这是我向其发送请求
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.org中的register\u rest\u 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
经过测试,效果良好。下面是注册自定义端点的完整代码以及如何调用它
<?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