# Random Post REST Endpoint

> Adds a public /wp-json/site/v1/random endpoint that returns one random published post with its title, link and excerpt, for "surprise me" buttons or widgets.

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

## Code

```php
add_action( 'rest_api_init', function () {
    register_rest_route( 'site/v1', '/random', array(
        'methods'             => WP_REST_Server::READABLE,
        'permission_callback' => '__return_true',
        'callback'            => function () {
            $ids = get_transient( 'wpide_random_post_ids' );

            if ( false === $ids ) {
                $ids = get_posts( array(
                    'post_type'      => 'post',
                    'post_status'    => 'publish',
                    'posts_per_page' => 500,
                    'fields'         => 'ids',
                    'no_found_rows'  => true,
                    'has_password'   => false,
                ) );
                set_transient( 'wpide_random_post_ids', $ids, HOUR_IN_SECONDS );
            }

            if ( ! $ids ) {
                return new WP_Error( 'no_posts', 'No posts found.', array( 'status' => 404 ) );
            }

            $post = get_post( $ids[ array_rand( $ids ) ] );

            return rest_ensure_response( array(
                'id'      => $post->ID,
                'title'   => get_the_title( $post ),
                'link'    => get_permalink( $post ),
                'excerpt' => wp_strip_all_tags( get_the_excerpt( $post ) ),
            ) );
        },
    ) );
} );

add_action( 'save_post_post', function () {
    delete_transient( 'wpide_random_post_ids' );
} );
```

## Notes

The list of candidate IDs is cached for an hour and refreshed when you publish or update a post.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Random Post REST Endpoint" 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/
