I have attempted to register the route, tried all sorts of different parameters, feel my code looks like many of the examples on this site, but can’t figure out why it doesn’t work.
//Register REST Route
add_action('rest_api_init', 'add_advent_api');
function add_advent_api()
{
register_rest_route('adventapi/v1', '/adventapi/', array(
'methods' => 'WP_REST_Server::READABLE',
'callback' => function () {
return 'hello';
},
'args' => array(
'adventyear' => array(
'required' => true,
'type' => 'integer',
'description' => 'Year required',
'minimum' => 1972,
'maximum' => 9999,
),
'adventday' => array(
'required' => true,
'type' => 'integer',
'minimum' => 1,
'maximum' => 24,
),
),
'permission_callback' => function () {
return true;
}
));
}
function advent_query(WP_REST_Request $request)
{
return 'i work';
/* $adventyear = $_GET['adventyear'];
$adventday = $_GET['adventday'];
$args = array(
'post_type' => 'advent',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'advent_year',
'value' => $adventyear,
),
array(
'key' => 'advent_day',
'value' => $adventday,
),
),
);
$query = new WP_Query($args);
if ($query->have_posts()) {
echo 'i ahve posts';
} else {
echo 'No Results';
} */
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
There’s an issue in your code: The HTTP method is not valid because WP_REST_Server::READABLE is a class constant, hence it should not be wrapped in quotes:
register_rest_route( 'adventapi/v1', '/adventapi/', array(
// 'methods' => 'WP_REST_Server::READABLE', // wrong
// 'methods' => "WP_REST_Server::READABLE", // wrong
'methods' => WP_REST_Server::READABLE, // correct
// ... other args.
) );
You should also ensure that you use the correct request/HTTP method as well as correct endpoint URL, e.g. https://example.com/wp-json/adventapi/v1/adventapi, when making requests to the API.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0