Displaying random posts to visitors is an excellent strategy to boost user engagement on your website. After researching extensively, I’ve summarized three methods to integrate random posts into a WordPress site, each with distinct advantages. My website, Shuijing Yiye, currently uses the third method.
Why Display Random Posts?
My original plan was to showcase curated lists of standout articles. However, as my site’s article library has grown, maintaining these manual lists has become a tedious chore, and I often neglect to update them for long periods. Related posts are highly appealing to visitors seeking solutions to specific problems, while random posts can capture the attention of casual visitors with no clear browsing goal.
Admittedly, a trending posts list is the optimal way to recommend content. Yet, implementing and maintaining a trending posts feature is far more complex. I attempted it for a while but eventually abandoned the project.
Without further ado, let’s dive into the three methods.
Contents
- The Principle of Fetching Random Posts
- Adding Code Directly to Theme Templates
- Using Dedicated Plugins
- Modifying the Theme’s
functions.phpFile
0. The Principle of Fetching Random Posts
WordPress’s
get_posts() function, used for querying posts, includes an orderby parameter that defines the sorting criteria for retrieved posts. By default, posts are sorted by their publication date—this is the standard sorting for WordPress homepage, category archive, and tag archive pages. The orderby parameter also accepts the value rand, which leverages MySQL’s RAND() function to generate a random sorting order.Here is the basic usage:
$args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish' ); $rand_posts = get_posts( $args );
This code retrieves 5 randomly sorted published posts.
A critical note: omitting the
post_status parameter may result in draft posts and other non-published content being displayed alongside live articles.1. Adding Code Directly to Theme Templates
The most straightforward approach is to modify your theme’s template files and insert the following code snippet at your desired location.
php
<ul> <?php $args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish' ); $rand_posts = get_posts( $args ); foreach( $rand_posts as $post ) : ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?> </ul>
This renders an unordered list of 5 random posts, each linked to its full article.
Pros
- Direct implementation: Code is added precisely where you want the random posts to appear.
- High customizability: Full control over the display position and HTML structure.
- Lightweight: Minimal server resource consumption.
Cons
Modifications will be overwritten when you update or switch your theme, unless you are using a child theme (child themes preserve custom code during parent theme updates).
2. Using Dedicated Plugins
The WordPress Plugin Directory hosts a wide selection of random post plugins. Below are some actively maintained and feature-rich options.
- AJAX Random Posts
- Free of charge.
- Fetches random posts via AJAX after the page loads, ensuring compatibility with caching plugins such as WP Super Cache. Random posts refresh with each visit, even on statically cached pages.
- Highly customizable: configure the number of posts, HTML markup, and displayed elements (post links, titles, categories, dates, etc.).
- Advanced Random Posts Widget
- Free of charge.
- Extensive customization: supports post thumbnails (custom dimensions available, though basic rendering may lack polished styling), custom-length excerpts, category and date filters. Compatible with the
get_the_imagefunction and multiple widget areas.
- Random Post for Widget
- Free and lightweight.
- Customizable post count; allows excluding posts by specific IDs.
- WPSIREN Random Post by Click
- Free of charge.
- Unique feature: displays a button that opens a random post when clicked, with full customization options for button styling.
- Random Post
- Random Posts Widget Configurable
- Free of charge.
- Basic customization: adjust the number of displayed posts.
Pros
Quick and user-friendly: No coding knowledge required for installation and basic configuration.
Cons
- Slight increase in server resource usage compared to manual code implementation.
- Customization capabilities are limited by the features of the chosen plugin.
3. Modifying the Theme’s functions.php File
Note: This method is compatible with PHP 5.2 and later.
My objective was to add a custom “Random Posts” widget to the WordPress dashboard’s Widgets menu, allowing me to add it to the site sidebar as a functional widget.
My WordPress installation already has a substantial number of plugins, and I wanted to avoid adding more to prevent excessive server strain. Therefore, I created a custom widget class and added it to my theme’s
functions.php file.Simply paste the code below (or a customized version) into your theme’s
functions.php file. If your active theme does not have a functions.php file, you can create one in the theme’s root directory. Essential: Start the file with <?php and end it with ?>.Once successfully implemented, the custom Random Posts widget will appear in the WordPress dashboard under Appearance > Widgets. You can add it to a sidebar widget area and configure the widget title and the number of posts to display.
Complete Code (Comments marked with //)
php
/**
* Random_Posts widget class
*
* Author: haoxian_zeng <http://cnzhx.net/ >
* Date: 2013.05.14, cnzhx2011 1.0
*/
//--------------- Register the custom widget
class WP_Widget_myRandom_Posts extends WP_Widget {
function __construct() {
$widget_ops = array(
'classname' => 'widget_my_random_posts',
'description' => __( 'A customized random posts widget for Shuijing Yiye. The cnzhx customized random posts widget.' )
);
parent::__construct( 'random-posts', __( 'Random Posts' ), $widget_ops );
$this->alt_option_name = 'widget_my_random_posts';
}
function widget( $args, $instance ) {
global $randomposts, $post;
extract( $args, EXTR_SKIP );
$output = '';
// Set the widget title
$title = apply_filters(
'widget_title',
empty( $instance['title'] ) ? __( 'Random Posts' ) : $instance['title']
);
// Set the number of posts to display
if ( ! $number = absint( $instance['number'] ) ) {
$number = 5;
}
// WordPress database query: fetch random published posts using the 'rand' orderby parameter
$randomposts = get_posts( array(
'number' => $number,
'orderby' => 'rand',
'post_status' => 'publish'
) );
// Begin constructing the output markup
// Output standard widget wrapper opening
$output .= $before_widget;
// Output widget title
if ( $title ) {
$output .= $before_title . $title . $after_title;
}
// Start random posts list
$output .= '<ul id="randomposts">';
if ( $randomposts ) {
foreach ( (array) $randomposts as $post ) {
$output .= '<li><a href="' . get_permalink() . '">' . esc_html( $post->post_title ) . '</a></li>';
}
}
$output .= '</ul>';
// Output standard widget wrapper closing
$output .= $after_widget;
// Render the final output to the page
echo $output;
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title'] );
$instance['number'] = absint( $new_instance['number'] );
$alloptions = wp_cache_get( 'alloptions', 'options' );
if ( isset( $alloptions['widget_my_random_posts'] ) ) {
delete_option( 'widget_my_random_posts' );
}
return $instance;
}
// Render the widget settings form in the WordPress dashboard
function form( $instance ) {
$title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
$number = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5;
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input
class="widefat"
id="<?php echo $this->get_field_id( 'title' ); ?>"
name="<?php echo $this->get_field_name( 'title' ); ?>"
type="text"
value="<?php echo $title; ?>"
/>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of posts to show:' ); ?></label>
<input
id="<?php echo $this->get_field_id( 'number' ); ?>"
name="<?php echo $this->get_field_name( 'number' ); ?>"
type="number"
value="<?php echo $number; ?>"
size="3"
/>
</p>
<?php
}
}
// Register the custom random posts widget
add_action( 'widgets_init', function() {
return register_widget( 'WP_Widget_myRandom_Posts' );
} );Pros
- Resource efficiency: Consumes fewer server resources than plugin-based solutions, while being slightly more resource-intensive than direct template edits.
- Unmatched customizability: Full control over every aspect of the widget’s functionality and appearance.
Cons
Implementation is more technically involved compared to the other two methods.
How to Increase Organic Traffic to Your WordPress Blog for Free (2026 Proven Playbook)
TL;DR
After tracking data from 300+ WordPress sites and growing my own blog from 120 to 5,800+ mo...
WordPress Security: Is Your Site Protected? [2026 Essential Checklist]
Is your WordPress site safe? Follow our essential 2026 security checklist. Learn how to secure hosting, enforce HTTPS, strengthen logins, manage plugins, set backups, and prevent hacking.

