Skip to content

Creating a WordPress Widget to Show a Random Post

Making a widget to show a random post uses two underlying concepts you need to get familiar with to be good at WordPress development: making use of WP_Query objects, and making widgets. If you’ve not checked them before, check out our Quick Guides which more thoroughly introduce both:

If you have, check out this video where I explain the pretty simple process I use to making a Random Post Widget:

How to Show Random Posts in WordPress

The core thing our widget will do is pull a random post from our WordPress database. (Specifically, we’ll be pulling posts whose post type is Post—that is, “blog posts” as opposed to Pages or any custom post type.)

Doing this requires us to use WP_Query. If you’re new to that part of WordPress, you can learn all about it in our free course on using WP_Query.

What makes pulling a random post possible is setting the query’s orderby property to rand. And here’s the full query:

$q_args = array(
	'orderby'        => 'rand',
	'posts_per_page' => '1',
);
$query = new WP_Query( $q_args );

That’s the basics of how to query for a random WordPress post in the WordPress database. The rest of this demo will show you how to build out a widget with that behavior.

How to Make a Random Post WordPress Widget Step-by-Step

  1. Follow the steps listed in the first Quick Guide about widgets.
  2. At the start of the widget method, add the line $query = new WP_Query. This will create for you a new object, $query, an instantiation of the WP_Query class (see the WP_Query link in further reading if that confuses you).
  3. Add argument to the WP_Query line. That means to add to the line above so it now reads: $query = new WP_Query( $q_args );. Then you’ll also need to create the $q_args variable. That’ll look like:
    $q_args = array(
    			'orderby'        => 'rand',
    			'posts_per_page' => '1',
    
    		);

    What that does is create some arguments. posts_per_page makes our WP_Query only return one item. orderby => 'rand' makes the function get a random one (by putting all of them into a random order).

  4. Then we need to make a loop. What this means is that we need to use while ($query->have_posts()) to contain a series of instructions. The first of those instructions will be $query->the_post() which “primes” the post for us to access with functions like the_title(). Then we’re going to replace the display directions from the last post, so the title and excerpt of the post is shown. That leads to a block like this:
    echo $args['before_widget'];
    echo $args['before_title'];
    the_title();
    echo $args['after_title'];
    echo get_the_excerpt();
    echo $args['after_widget'];
  5. We make sure that after the end of the loop we call wp_reset_postdata(). This undoes our “pollution” in $query->the_post() so that the rest of the site doesn’t act funky because of our widget. It’s just good hygiene.

Full Code for Making our Widget

class QG_Widget extends WP_Widget {

	/**
	 * Sets up the widgets name etc
	 */
	public function __construct() {
		$widget_ops = array( 
			'classname' => 'qg_widget',
			'description' => 'This is a widget for a quick guide',
		);
		parent::__construct( 'qg_widget', 'Quick Guide Widget', $widget_ops );
	}

	/**
	 * Outputs the content of the widget
	 *
	 * @param array $args
	 * @param array $instance
	 */
	public function widget( $args, $instance ) {
		$q_args = array(
			'orderby'        => 'rand',
			'posts_per_page' => '1',

		);
		$query = new WP_Query( $q_args );
		while ($query->have_posts()) {
			$query->the_post();
			echo $args['before_widget'];
			echo $args['before_title'];
			the_title();
			echo $args['after_title'];
			echo get_the_excerpt();
			echo $args['after_widget'];
		}
		wp_reset_postdata();
	}
}

add_action( 'widgets_init', function(){
	register_widget( 'QG_Widget' );
});

Further Reading on Widgets and WP_Query

If you’d like to learn more on the core technical elements of this demo, here are two of our free courses to check out—on using widgets and using WP_Query, respectively:

Creating WordPress Widgets: The Complete Guide

 

WP_Query: Understand it, Love it!

Thanks for reading!

Yay! 🎉 You made it to the end of the article!
David Hayes

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Jim
October 15, 2019 10:53 am

Thanks!

Works perfectly and makes sense. A lot of bad info on this on the internet out there on this topic.

Cheers

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!

1
0
Would love your thoughts, please comment.x

Most Searched Articles

Best JavaScript Libraries and Frameworks: Try These 14 in 2024

In this post, we look at the best JavaScript libraries and frameworks to try out this year. Why? Well, with JavaScript being available in every web browser, this makes it the most accessible programming language of ...

20 Best Free WordPress Themes for 2024 (Responsive, Mobile-Ready, Beautiful)

If you're looking for only the best free WordPress themes in the market for this year, then you're in the right place. We have more than enough such themes for you right ...

12 Best WordPress Hosting Providers of 2024 Compared and Tested

Looking for the best WordPress hosting that you can actually afford? We did the testing for you. Here are 10+ best hosts on the market ...

Handpicked Articles

How to Make a WordPress Website: Ultimate Guide for All Users – Beginners, Intermediate, Advanced

Many people wonder how to make a WordPress website. They’ve heard about WordPress, its incredible popularity, excellent features and designs, and now they want to join the pack and build a WordPress website of their own. So, where does one get ...

How to Start an Ecommerce Business: Ultimate Guide for 2024

Is this going to be the year you learn how to start an eCommerce business from scratch? You’re certainly in the right place! This guide will give you a roadmap to getting from 0 to a fully functional eCommerce business. ...