Skip to content

Instantly share code, notes, and snippets.

@abrudtkuhl
Created March 21, 2016 20:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abrudtkuhl/df73990cb37b426037c5 to your computer and use it in GitHub Desktop.
Save abrudtkuhl/df73990cb37b426037c5 to your computer and use it in GitHub Desktop.
WordPress REST API - Get Random Post endpoint
<?php
/**
* Plugin Name: WP Slack REST API Backend
* Description: An example of using the WordPress REST API as a backend for a Slack Bot
* Author: Andy Brudtkuhl
* Author URI: http://youmetandy.com
* Version: 0.1
* Plugin URI: https://github.com/abrudtkuhl/heykramer
* License: GPL2+
*/
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' => 1) );
}
@hostedpixel
Copy link

hostedpixel commented Sep 25, 2016

Just letting you know you are missing a


);

on line 18

@caramboleyo
Copy link

Add orderby => rand to existing posts api endpoint:

function my_rest_post_collection_params($query_params) {
	$query_params['orderby']['enum'][] = 'rand';
	return $query_params;
}
add_filter('rest_post_collection_params', 'my_rest_post_collection_params');

Now this works:
/wp-json/wp/v2/posts?orderby=rand

@evokelektrique
Copy link

rest_{post_type}_collection_params

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment