# /random/ Link to a Random Post

> Makes /random/ open a random published post, a fun "Surprise me" link for menus that keeps readers exploring your archive.

- Type: PHP
- Runs: Run everywhere
- Category: [Redirects](https://wpide.com/library/category/redirects/)
- Tags: redirects, random, engagement
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/random-post-link/

## Code

```php
// /random/ opens a random published post: a fun "Surprise me" link for menus.
$wpide_random_path = 'random';
// Pick from this many of your newest posts.
$wpide_random_pool = 500;

add_action( 'template_redirect', function () use ( $wpide_random_path, $wpide_random_pool ) {
    if ( ! is_404() ) {
        return;
    }

    $path = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
    $want = (string) wp_parse_url( home_url( '/' . trim( $wpide_random_path, '/' ) ), PHP_URL_PATH );

    if ( strtolower( untrailingslashit( $path ) ) !== strtolower( untrailingslashit( $want ) ) ) {
        return;
    }

    $ids = get_transient( 'wpide_random_post_pool' );

    if ( ! is_array( $ids ) ) {
        $ids = get_posts( array(
            'post_type'           => 'post',
            'posts_per_page'      => max( 1, (int) $wpide_random_pool ),
            'has_password'        => false,
            'ignore_sticky_posts' => true,
            'no_found_rows'       => true,
            'fields'              => 'ids',
        ) );
        set_transient( 'wpide_random_post_pool', $ids, 6 * HOUR_IN_SECONDS );
    }

    if ( ! $ids ) {
        return;
    }

    nocache_headers();
    wp_safe_redirect( get_permalink( $ids[ array_rand( $ids ) ] ), 302 );
    exit;
} );

add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) {
    if ( 'post' === $post->post_type && ( 'publish' === $new_status || 'publish' === $old_status ) ) {
        delete_transient( 'wpide_random_post_pool' );
    }
}, 10, 3 );
```

## Notes

Picks from your 500 newest posts by default; only used when no real page has that address.

## How to use it

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