FB Pixel

Display a random post using a custom URL

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 ); 		} 	} }

How healthy is your WordPress site? Check it free, right on the page. No login required. Free · results in seconds · no credit card