Reputation: 7299
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!
Upvotes: 1
Views: 1085
Reputation: 432
Below is full code to register custom end point and how to call it.
<?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';
}
} );
?>
How to call your custom end point.
http://domain_name/wp-json/custom_apis/v1/get_helloword
Upvotes: 0
Reputation: 1475
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.
Upvotes: 1