WordPress REST API, Get Random Post endpoint

In the following snippet, you can register a new endpoint in the API to access random posts.

This can be configuring to work with any post-type.  You’ll just updating the get_posts array accordingly.  Enjoy!

You’ll want to put this inside your functions.php inside your Theme, or create a plugin.  If you’re extending the WordPress REST API further you should probably just create a plugin.

add_action( 'rest_api_init', function () {
    register_rest_route( 'api', '/any', array(
        'methods'   =>  'GET',
        'callback'  =>  'get_random',
    ) );
function get_random() {
    return get_posts( array( 'orderby' => 'rand', 'posts_per_page' => 3) );