I'm using the following code to register a custom WordPress endpoint:
add_action('rest_api_init', function(){
register_rest_route('custom', array(
'methods' => 'GET',
'callback' => 'return_custom_data',
));
});
function return_custom_data(){
return 'test';
}
However, this is the result I'm getting when sending a request to it:
{'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/'}]}}
It does recognize the endpoint, but the data I specified in the callback isn't returned.
Any suggestions?
Thanks!
Please check register_rest_route
document in wordpress.org there are four arguments you can pass in that function. First two arguments are required.
Use below code to work with custom endpoint
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";
}
Endpoint will be http://localhost/index.php/wp-json/custom/v2
Tested and works well.