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

The Landing Page Builds service includes:

  • Unlimited page builds for one monthly rate
  • Dedicated account manager
  • Dedicated WordPress developer
  • At least 2 hours of daily dev time
  • Daily progress reports
  • Find out more here

The Content Edits Plan includes:

  • Unlimited content edits
  • White label help desk
  • Support ticket dashboard
  • 24/7 team of WordPress experts
Plus, everything in our Maintenance Plan:
  • Visual Validator WordPress updates
  • 90 days of off-site backups
  • Daily security scans and malware cleanup
  • Maintenance dashboard
  • Find out more here

The Maintenance Plan includes:

  • Visual Validator WordPress updates
  • 90 days of off-site backups
  • Daily security scans and malware cleanup
  • Maintenance dashboard
  • Find out more here