How to Display Random Posts in WordPress: The Complete Guide

Have you noticed that if you’re actively posting new articles on your website or blog, old articles get buried and receive less attention from new visitors who come to your blog?

There are several solutions to reviving these articles, such as installing a plugin to automatically share older posts on social media. Or… you can display random posts on your sidebar, or inside a post, or even add a link to a random post on your navigation area.

Display Random Posts in WordPress: The Complete Guide

 

In this article, I’m going to talk about how can random posts help revive old posts, which sites this method works the best on and of course, how to display random posts in WordPress.

Without further ado, let’s get started.

How Can Random Posts Help Your Website

As I mentioned it above, if you are posting a lot on your website or blog, older articles disappear from your front page, and as with google, not many go to the 4th or 5th page in your main archive.

So if you display random articles on your sidebar, for example, there’s a chance that your visitors will find one of those articles useful.

This method works best on magazine sites or sites with multiple authors and lots of content.

Also, let’s not forget, that if someone finds one or more of the articles displayed interesting, they might read it, and that reduces bounce rate and gives you more chance of converting the visitor into an email subscriber and loyal fan.

How to Display Random Posts in WordPress

Now that we talked about how these randomly displayed posts can help your blog, let’s see how can we actually display them. Below, I’ll show you 3 ways you can display these posts.

Displaying Random Posts Inside a Post

In order to be able to display random posts inside a post, we’ll need to create a custom shortcode.

Shortcodes allow us to run custom scripts or queries inside a post, page or sidebar.

If you want to learn more about shortcodes in WordPress, there’s a great article on Smashing Magazine about them.

Here’s how our shortcode will look like:

[random-posts posts=5 cat=themes,plugins]

It accepts two variables, the number of posts, and from which category those posts should be from.

The first thing we need to create is the function that will process the information from the shortcode, and retrieve the posts from the database and then displays them. You can place these functions inside your theme’s functions.php or if you have a site specific plugin, then use that.

The function we will create will be called random_posts_function() {} and inside this function, we need to first, extract the values from our shortcode. In this case, the number of posts, and the categories.

<?php

// The Shortcode's Function.
function random_posts_function($atts) {
	// Extracting Attributes
	extract(shortcode_atts(array(
		'posts' => 1,
		'cat' => '',
	), $atts));
}

After we extracted the values, we can create our custom query:

<?php
// Creating a custom query
query_posts( 
	array( 
		'orderby' 				=> 'rand', 
		'ignore_sticky_posts' 	=> 1, 
		'category_name' 		=> $cat, 
		'posts_per_page' 		=> $posts 
	) 
);

In the above query, we ask WordPress to return our $posts number of posts, from the $cat category, in a RAND ( random ) order. And also ignoring the sticky posts.

Now that we have our query, we can make a list of them like so:

<?php
// Opening an unorderd list ( <ul> )
$return_string = '<ul class="randomPosts">';

	// creating a list of returned posts
	if (have_posts()) :
		while (have_posts()) : the_post();
			$return_string .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
		endwhile;
	endif;

// closing the opened unordered list ( </ul> )
$return_string .= '</ul>';`

This will display a list of our randomly selected posts.

Now all that’s left is, to reset the WordPress query, so it can continue to load the page and to return the list of posts we’ve built.

// resetting the WordPress query
wp_reset_query();

// displaying the list of random posts
return $return_string;

And we are done without function.

Now that we have our function for the shortcode, we can register it and add it to the WordPress setup process.

// Creting the Shortcodes
function register_shortcodes(){
	add_shortcode('random-posts', 'random_posts_function');
}

// Registering the Shortcodes
add_action( 'init', 'register_shortcodes');

And we’re done! Now if you use the following shortcode inside a post, then you should see 5 or as many as you’ve set random posts to appear as a list.

Displaying Random Posts in the Sidebar

To display random posts in your sidebar, there’s awesomely easy to use plugin called Advanced Random Posts Widget.

Advanced-Random-Posts-Widget

Advanced Random Posts Widget adds a flexible and advanced random posts widget.

After you installed the plugin and added the widget to your sidebar, you should be able to see the settings for it. 6 tabs.

  • General
  • Posts
  • Taxonomy
  • Thumbnail
  • Extras
  • Custom CSS

The General Settings tab contains the basics. Title, title URL ( optional ), a custom CSS Class, and custom HTML Before and After the Posts. These appear after and before the list of the random posts.

 

The Second Tab contains settings such as, to ignore sticky posts, the number of posts to display, how many posts to skip, which type of posts to display and post with what status should be displayed. ( Published, future, draft, pending, private, trash, auto-draft and inherit. )

 

The Third Tab contains the settings to limit the random posts to only some specific categories, or tags or other custom taxonomies.

 

The Fourth Tab is all about the thumbnails. To display a thumbnail or, not and if yes, which size to use or you can specify a custom size. Also to which side the thumbnail should be aligned to. ( left, right, center )

 

The Fifth Tab holds settings like, to show a post excerpt ( + the length ), date, modified date and to use a relative date like, 5 days ago instead of May 5, 2015, for example.

 

The Sixth Tab is for custom CSS, in case you want to add some custom style and/or modification to how the widget looks on the front end.

 

Here are the CSS selectors you can use in order to change the look of the widget.

/* ul */
.arpw-ul {}

/* li */
.arpw-li {}

/* title */
.arpw-title {}

/* thumbnail */
.arpw-thumbnail {}

/* date */
.arpw-time {}

/* excerpt */
.arpw-summary {}

Also, if you have any issues with the custom styles, don’t forget to check the FAQ page. As it is now, it shows a method for custom CSS, where you need to add the CSS into your theme’s style.css, and also need to remove the widget’s original styles with a PHP snippet.

Thou I believe that wasn’t updated when the newest version came out. Otherwise, what would be the point of the Custom CSS tab, right?

To add a random post link to your navigation menu, first, you need the name of the menu location which you want to add this button/link to.

Usually, it’s the name you see when you assign navigation menus in the appearance -> menu section, ( primary, secondary, mobile and so on. ) but with a –menu added to them. Like primary-menu

or so.

 

If you have this, then we can go ahead and create the function that will display the button/link for the random posts. The link on the button/link will change on each page load.

Same as with the inside posts, these functions can go either into your theme’s function.php or into a site specific plugin.

function random_post() {

	// Querying a random post
	$posts = get_posts('post_type=post&orderby=rand&numberposts=1');

	// Getting the URL of the random posts
	foreach($posts as $post) {
		$postlink = get_permalink($post);
	}

	// Returning a clickable link to the random post
	return "<a href='" . $postlink . "' title='" . get_the_title($post) . "'>Random Post</a>";
}

Now that we have our button/link with the random posts, all we need to do is to add it to our navigation menu. This is where we need the name of the menu locations.

add_filter('wp_nav_menu_items','add_custom_in_menu', 10, 2);
function add_custom_in_menu( $items, $args ) {
    // Don't forget to change "primary-menu" to the location name of your navigation menu
    if( $args->theme_location == 'primary-menu')  { 
        $items .=  '<li>' . random_post() . '</li>';
	}
    return $items;
}

This will add our newly created link/button to the end of our navigation menu. See the image below:

 

Each time you click on the button, it’ll redirect you to a random post.

Random posts might not be the best solution to revive older posts on your website, but none the less, it can help you one way or another. And as you can see, it’s not that hard to display them in your posts, sidebar or on your navigation menu.

If you found this tutorial useful, feel free to share it with your friends and followers. And if you have any questions related to this, or suggestion maybe, please do leave a comment down below!

Get more stuff like this

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for subscribing.

Something went wrong.

Add Comment

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for subscribing.

Something went wrong.