Display Random Posts in WordPress

Watch out! This tutorial is over 8 years old. Please keep this in mind as some code snippets provided may no longer work or need modification to work on current systems.
Tutorial Difficulty Level    

This method requires you to add code to your WordPress theme files, so exercise caution.

First thing you need to do is add this code in your theme’s functions.php

function wpb_rand_posts() { 

$args = array(
	'post_type' => 'post',
	'orderby'	=> 'rand',
	'posts_per_page' => 5, 
	);

$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {

$string .= '<ul>';
	while ( $the_query->have_posts() ) {
		$the_query->the_post();
		$string .= '<li><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>';
	}
	$string .= '</ul>';
	/* Restore original Post Data */
	wp_reset_postdata();
} else {

$string .= 'no posts found';
}

return $string; 
} 

add_shortcode('wpb-random-posts','wpb_rand_posts');
add_filter('widget-text', 'do_shortcode');

This code simply creates a function that displays 5 random posts. It then creates a shortcode so that you can easily display random posts anywhere on your site. Lastly, it enables shortcodes to be executed inside WordPress widgets so that you can use shortcode inside a text widget.

Now you can easily display random posts inside a WordPress post, page, or text widget using the shortcode [wpb-random-posts].