Some time ago, after announcing the WordPress 5.1 first beta on the WordPress Brasil Facebook group, a user asked when we’d have the option to random order the posts on WordPress REST API. I explained that core doesn’t need to allow it because it could be done through a custom code.

The code below uses the filter rest_{$this->post_type}_collection_params to include rand as an entry of the array which enumerates the possible values for ordination. This filter is used in the end of the get_collection_params method, inside the WP_REST_Posts_Controller class, as you can see here. The {$this->post_type} filter part is variable and in the code I used it to change the posts list.

In order to apply the random order, you only have to call /wp-json/wp/v2/posts?orderby=rand. If you’re using some cache solution, the final result can be affected.

<?php
/**
 * Plugin Name: REST API - Post list randomize
 * Description: Randomize the content list in REST API passing `orderby=rand` as parameter.
 * Version:     1.0.0
 * Author:      Felipe Elia | Codeable
 * Author URI:  https://codeable.io/developers/felipe-elia?ref=qGTOJ
 */

/**
 * Add `rand` as an option for orderby param in REST API.
 * Hook to `rest_{$this->post_type}_collection_params` filter.
 *
 * @param array $query_params Accepted parameters.
 * @return array
 */
function add_rand_orderby_rest_post_collection_params( $query_params ) {
	$query_params['orderby']['enum'][] = 'rand';
	return $query_params;
}
add_filter( 'rest_post_collection_params', 'add_rand_orderby_rest_post_collection_params' );

You only have to save the code as a PHP file and put it into the plugins directory. The code is also available as a gist.


If you have any trouble deploying this code or with anything related to WordPress, give a look at my Codeable Profile and click on that Hire button!