Allow Random Order in REST API Post Lists
Lets REST API clients request posts with orderby=rand, for example to show a few random articles in an app, which WordPress does not allow by default.
Opens WPIDE on
Code
add_filter( 'rest_post_collection_params', function ( $params ) {
if ( isset( $params['orderby']['enum'] ) && ! in_array( 'rand', $params['orderby']['enum'], true ) ) {
$params['orderby']['enum'][] = 'rand';
}
return $params;
} );
add_filter( 'rest_post_query', function ( $args, $request ) {
if ( 'rand' === $request->get_param( 'orderby' ) ) {
$args['orderby'] = 'rand';
}
return $args;
}, 10, 2 );
Notes
Random ordering cannot be cached well by CDNs; keep per_page small.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.