# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: rest-api, random, query
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/rest-allow-random-order/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Allow Random Order in REST API Post Lists" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
