/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.
Opens WPIDE on
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
- 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.