<?php
/*
http://example.com/wp-json/namespace/v2/my-route?foo=bar
{"success":true,"request":{"foo":"bar"},"count":11,"posts":[298,297,296,295,294,105,103,101,99,97,1]}
*/
if ( ! class_exists( 'MyRoute' ) ):
class MyRoute {
const ENDPOINT_NAMESPACE = 'namespace/v2';
public function init() {
add_action( 'init', array ( $this, 'add_endpoint' ), 0 );
}
public function add_endpoint() {
add_action('rest_api_init', function () {
// http://example.com/wp-json/namespace/v2/my-route?foo=bar
register_rest_route( static::ENDPOINT_NAMESPACE, '/my-route', array (
'methods' => 'GET',
'callback' => array($this, 'wp_json_namespace_v2__my_route'),
'permission_callback' => function (WP_REST_Request $request) {
return true;
}
));
});
flush_rewrite_rules(true); // FIXME: <------- DONT LEAVE ME HERE
}
/**
* Handle the route request
* @param $request
*
* @return WP_REST_Response
*/
function wp_json_namespace_v2__my_route($request)
{
// json-api params
$parameters = $request->get_query_params();
// default search args
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => -1,
// limit to only ids
'fields' => 'ids',
);
// run query
$posts = get_posts($args);
// return results
$data = array(
'success' => true,
'request' => $parameters,
'count' => count($posts),
'posts' => $posts,
);
return new WP_REST_Response($data, 200);
}
}
$wpMyRoute = new MyRoute();
$wpMyRoute->init();
endif; // MyRoute
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.