You can add the code below to your theme’s functions.php file between the PHP tags. The PHP tags look like this: <?php…..?>
function wpdean_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('wpdean-random-posts','wpdean_rand_posts');
add_filter('widget_text', 'do_shortcode');
This code will create a function for displaying five random posts from your site and enable the shortcode [wpdean-random-posts]. You can now add this shortcode inside any post, page, or text widget to display a list of five random posts.
If you’d like to display more (or less) posts, just change the “5” in this line of the code snippet to the number you want:
‘posts_per_page’ => 5
Because making a mistake in the functions.php file can break your site, it’s only recommended for users with some technical expertise. If you’re a beginner, then you’ll be better off using a plugin to create a display of random posts on your site.
Display Random Posts in WordPress Using a Plugin
The Advanced Random Posts Widget plugin provides two different options for adding a list of random posts to your WordPress site. You can use the widget to add the list to your sidebar or you can use the shortcode to add the list anywhere on your site.
Let’s take a closer look at each option below.
Display Random Posts in Sidebar
Once installed, the Advanced Random Posts Widget plugin adds a widget to your WordPress dashboard. After clicking on Appearance > Widgets, you’ll see a widget labeled “Random Posts.” Drag and drop it into your sidebar.
COMMENTS