How to Display Random Posts in WordPress


Display Random Posts in WordPress Using Code

Add the shortcode function in your active theme functions.php file

function 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() ) {
   $string .= '<li><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>';
  $string .= '</ul>';
  /* Restore original Post Data */
 } else {

 $string .= 'no posts found';

 return $string; 

add_filter('widget_text', 'do_shortcode');

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

Related Post

Latest Post

Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.