Halloween Sale 15% off Ends in See the plans
PHP

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

Don’t have WPIDE yet? Install it on your site

Code

// /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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.