How to Display Random Posts in WordPress

Hello Friends, Do you want to display random posts in WordPress? Display Random Posts gives your users a chance to discover more of your content on the website. In this article, we will show you how to easily display random posts in WordPress Website.

However, most users will not get to see your older articles. If you have been running your site for quite some time now, then your older articles will not be prominently displayed anywhere.

Having said that, let’s see how you can easily display random posts in WordPress Website.

Display Random Posts in WordPress Using Code

In this method requires you to add code to your WordPress theme files. First thing you need to do is add this code in your theme’s functions.php file or a site-specific plugin.

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.

[php]
function ef_wd_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(‘ef_wd-random-posts’,’ef_wd_rand_posts’);
add_filter(‘widget_text’, ‘do_shortcode’);

[/php]

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

That’s all, we hope this article helped you learn how to display random posts in WordPress Website. If you liked this article, then please Share and Comments.

Display Random Posts in WordPress