Last week a user on the WordPress subreddit was asking about displaying a random post using a unique permanent link – something like domain.com/random-post/
, for example. This is something that can be done via the pre_get_posts
filter with just a few lines of code.
First, we’ll add the filter hook and our function:
add_filter( 'pre_get_posts', 'gowp_random_post' ); function gowp_random_post( $query ) { ... }
The first thing we’ll do in our function is check to see if our desired URL is being used. If you want to use a different URL, just change this line accordingly:
add_filter( 'pre_get_posts', 'gowp_random_post' ); function gowp_random_post( $query ) { if ( 'random-post' == $query->get( 'name' ) ) { ... } }
Then, we’ll access the $wpdb
global to run an SQL query that returns the ID number of a random published post from the database. You could change this line to pull from a different post type as well (ie. pages, products, etc):
add_filter( 'pre_get_posts', 'gowp_random_post' ); function gowp_random_post( $query ) { if ( 'random-post' == $query->get( 'name' ) ) { if ( $post_id = $wpdb->get_var( "SELECT ID from $wpdb->posts WHERE post_type LIKE 'post' AND post_status LIKE 'publish' ORDER BY RAND() LIMIT 1;" ) ) { ... } } }
Finally, we’ll use the get_post()
function to create a $post
object of the random post and update the query vars so that this post is displayed as if it were visited directly:
add_filter( 'pre_get_posts', 'gowp_random_post' ); function gowp_random_post( $query ) { if ( 'random-post' == $query->get( 'name' ) ) { global $wpdb; if ( $post_id = $wpdb->get_var( "SELECT ID from $wpdb->posts WHERE post_type LIKE 'post' AND post_status LIKE 'publish' ORDER BY RAND() LIMIT 1;" ) ) { $post = get_post( $post_id ); $query->set( 'name', $post->post_name ); } } }
Hi,
I placed the code in my theme’s functions.php and created a link to (mysite)/random-post/ but it doesn’t work. Am I missing a step? Do I also need to create a blank page with slug random-post?
Hi James. The code should work as-is without any modification required. What happens when you visit /random-post/ ?
It leads to 404
Hmm. I just double-checked it and it works for me on a fresh install using a default theme. Do you have pretty permalinks enabled?