How to Display Random Posts in WordPress
When showing blog posts, WordPress websites most commonly display them descending by date. That way readers get to see the latest articles first. By taking advantage of this method, the number of views on those articles will quickly go up.
However, once the number of articles on your blog increases, your older posts will receive less and less traffic as they will be harder to reach under all the newer posts. This is beneficial if the content of your older posts becomes outdated, but detrimental if those posts contain evergreen content that readers will miss out on. This can skew your traffic statistics and affect how you approach your analytics reports. Another issue that can affect your traffic is readers wanting to locate additional information and leaving your site if that information proves too hard to locate. The most common ways of tackling these issues are adding internal links to your articles, showing all posts on the same page, or providing visitors with the option to view random posts. We will talk about the latter in this article and cover the following topics:
The best places to display random posts include the sidebar, the area below the post content, or within the footer. Adding a relevant random posts section on any of these three places can work wonders for enhancing the layout of your blog posts, and give your readers quick and effortless access to other articles. If you take the time to include appropriate metadata (e.g. categories, tags, or excerpts) next to the articles, you can help your visitors easily figure out which article to read next.
However, WordPress doesn’t possess a built-in functionality for displaying random posts. Currently, the only two ways of managing this are to use an appropriate WordPress plugin or to create custom code. In the sections below, we will take you through both methods. Our examples will focus on displaying random posts inside a sidebar, but the same methods could be applied to other locations on your site.
When wanting to add a certain feature or functionality to your WordPress website, you should always look for a suitable WordPress plugin first. Thanks to the abundance of good WordPress plugins, the chances of finding one to do what you want, in this case, display random posts, are very high. However, when hunting for a plugin, you should always broaden the search a bit and look for multipurpose plugins as well.
In this specific case, you should search for plugins that show random posts but also display recent posts or posts in general. And you can consider using redirection-related plugins. In the following section, we will show you two plugins that are well-suited for displaying random posts, even though their names might not indicate it.
Recent Posts Widget With Thumbnails
The Recent Posts Widget With Thumbnails plugin is an intuitive, light-weight plugin. It provides a widget for displaying recent posts based on the default WordPress widget called Recent posts. However, since it has the option to display posts in a random order, it is perfectly suited for our needs.
After installing the plugin, navigate to Appearance > Widgets, and find the Recent Posts with Thumbnails widget. Insert the widget inside the widget area of your choice and adjust its options to your preference.
The widget has quite a few options, but don’t be tempted to skip them. At least make sure to fill out the number of posts you wish to show and tick the checkbox next to the Show posts in random order? option. Apart from that, we took the time to insert a title for the widget and ticked the checkbox next to the Show thumbnail option, while creating the examples for this article. By using widget options, you can also opt to show the author, categories, publish date, excerpt, and comments for each of the random posts.
With the settings we choose, we got the following widget output.
Redirect URL to post
Some users might only want to display a single random post as opposed to a list of them. In that case, the best option would be using a button or a link that redirects to a random post. The plugin we picked to demonstrate this is the Redirect URL to Post plugin.
After installing it, this plugin allows you to insert a redirect link that leads to a random post. Furthermore, you can even specify where your readers will be directed by appending query parameters to the URL. That’s done using target and filter parameters. The target parameters are used to direct visitors to a random, oldest, previous, or a custom-set post. And the filter parameters, combined with the target ones, can help narrow down which of those posts can be selected for display. These filters can help you exclude certain posts, display random posts from a specific author, or even showcase posts that have a set number of comments already on them. However, as this topic is advanced, we suggest reading through the plugin’s documentation for more information. You should particularly focus on the examples of possible URLs to see how you can control the redirection.
After you’ve examined the documentation and decided how you want your redirect link to be, you should add it. As we mentioned previously, we will focus on adding random posts to the sidebar, but you can add yours anywhere you like.
To insert a random post to the sidebar, navigate to Appearance > Customize > Widgets. Then add a Text widget inside the widget area designated for the sidebar. Please note that the name of the widget area can vary depending on the theme you are using. In our case, we’re using the Lekker WordPress theme and the name of the widget area there is Main Sidebar.
After adding the Text widget, open its Text tab and click on the link button to add a link. In the following popup window, insert the redirect URL, link text, and, if you like, tick the checkbox next to the Open link in a new tab option. Then, press the Add Link button.
As you can see from the screenshots below, the redirect link we used is https://your-website.com/?redirect_to=random. This is just an example, so the part with your-website.com should be replaced with an actual URL.
Just using the Link Text field will net you a neat, straightforward look for the redirect link, as you can see on the following screenshot. However, you can also opt to insert some additional text to the Text widget.
Moreover, this plugin provides users with a custom redirect button shortcode that you can use inside the content of your pages or widgets. You can find more information on it in the documentation regarding the redirect button shortcode. And, if you aren’t sure what custom shortcodes are or how to use them, you can take a look at our article on custom shortcodes to learn more.
Once you’ve brushed up on your knowledge of custom shortcodes and their use, you can insert the redirect button shortcode in the place of your choosing. In our example, we will show you how you can insert the redirect button for random posts within a sidebar.
Start by navigating to Appearance > Widgets, then insert a Text widget inside your theme’s sidebar widget area. After that, add the shortcode call within the widget. At this point, you can just insert [redirect_to_post_button] to finish the job, as all the arguments will show their default values. However, for added customization, you can also insert arguments in the key=”value” form to specify some of the arguments.
In our example, we inserted text=”Click here to see a random post”. This specifies the text that will be written on the button. And we also added button_class=”random-post”. That adds a custom class to the button which we can use to stylize it.
Once you’ve inserted the redirect button shortcode, you might decide to add CSS to stylize it. Generally, that’s done to make this new functionality match with the style of the theme you are using, and ensure your site looks harmonious. Therefore, creating suitable CSS is done on a case-by-case basis as it depends on your current site design. And, once you’ve created the CSS, you should insert it in Appearance > Customize > Additional CSS.
For this article, we created CSS that makes the random posts button fit with Lekker, the theme we’re using. The CSS we created was specifically made for the random-post class we previously added to the button.
button.random-post { border-radius: 20px; position: relative; margin: 0 2px 2px 0; padding: 5px 20.5px; font-family: inherit; line-height: inherit; letter-spacing: 0.05em; background-color: #f55758; color: white; } button.random-post:hover { background: #e82a2a !important; color: #fff !important; cursor: pointer; } button.random-post:focus{ outline: none; }
Here’s how the button looked after inserting the CSS.
Another way of displaying random posts in WordPress involves the use of custom code. Because of that, the method explained in this section is geared towards the more experienced WordPress users. Level of difficulty aside, this method has a clear benefit—you can code the random posts section to fit your needs exactly. But keep in mind, when creating the code, you should review it carefully before adding it to your site. Any coding mistake could potentially break your website.
In this article, we included an example of code you can use to create a random posts section. The code should be added either in the functions.php file of your theme or inside a site-specific plugin. We will show the former method of adding below. As it requires the use of FTP, we suggest brushing up on it. We also suggest making a backup of your WordPress files, just in case. Having done so, let us proceed to the steps.
First, connect to your server using your FTP credentials and navigate to your root WordPress directory, often called public_html.
Then, navigate to the /wp-content/themes directory and click on your theme’s folder to open it. Locate the functions.php file within, right-click on it and select the View/Edit option.
Open the file using your preferred text editor and scroll to the bottom. Insert the following code at the end of the file.
function qode_random_posts() { global $post; $html = ''; $args = array( 'post_type' => 'post', 'orderby' => 'rand', 'posts_per_page' => 2, ); if ( isset( $post->ID ) && is_singular( 'post' ) ) { $args['post__not_in'] = array( $post->ID ); } $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { $html .= '<ul class ="post-holder">'; while ( $the_query->have_posts() ) { $the_query->the_post(); $html .= '<li class="post"><a href="' . get_permalink() . '">'; if ( has_post_thumbnail( $post->ID ) ) { $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); $html .= '<img class="featured-image" src="' . esc_url( $image[0] ) . '">'; } $html .= get_the_title() . '</a>'; $long_excerpt = get_the_excerpt(); if ( ! empty( $long_excerpt ) ) { $short_excerpt = substr( get_the_excerpt(), 0, 80 ); $excerpt = substr( $short_excerpt, 0, strrpos( $short_excerpt, ' ' ) ); $excerpt .= '[…]'; $html .= '<p>' . wp_kses_post( $excerpt ) . '</p>'; } $html .= '</li>'; } $html .= '</ul>'; wp_reset_postdata(); } else { $html .= '<div class="no-random-posts">' . esc_html__( 'No posts were found.', 'textdomain' ) . '</div>'; } return $html; } add_shortcode( 'random-posts', 'qode_random_posts' );
Afterward, save the changes you made and upload the edited file back to your server to override the current one.
Before we go farther, let us elaborate on the code we included above. To make it easier to follow, we simplified the code slightly and divided it into two parts.
Firstly, the code is equivalent to the following, shortened, version.
function qode_random_posts() { global $post; $html = ''; $args = array( 'post_type' => 'post', 'orderby' => 'rand', 'posts_per_page' => 2, ); if ( isset( $post->ID ) && is_singular( 'post' ) ) { $args['post__not_in'] = array( $post->ID ); } $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) { $html .= '<ul class ="post-holder">'; while ( $the_query->have_posts() ) { $the_query->the_post(); // Some code here } $html .= '</ul>'; wp_reset_postdata(); } else { $html .= '<div class="no-random-posts">' . esc_html__( 'No posts were found.', 'textdomain' ) . '</div>'; } return $html; } add_shortcode( 'random-posts', 'qode_random_posts' );
This code represents a shortcode called random-posts. It performs certain operations using the information that corresponds to the posts that matched a given query. And the query is quite simple, as it selects two random posts from the list of all published posts.
Additionally, if this shortcode is shown inside a post, then that same post can’t be chosen to avoid showing duplicate information. However, that restriction doesn’t apply if the shortcode is used on other types of pages. And in case that there are no published posts, a message stating No posts were found will be shown.
Secondly, to make sure all published posts are covered, we used the WordPress Loop. The inner part of the code, which you can see below, is responsible for showing the relevant data belonging to the two selected posts.
$html .= '<li class="post"><a href="' . get_permalink() . '">'; if ( has_post_thumbnail( $post->ID ) ) { $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); $html .= '<img class="featured-image" src="' . esc_url( $image[0] ) . '">'; } $html .= get_the_title() . '</a>'; $long_excerpt = get_the_excerpt(); if ( ! empty( $long_excerpt ) ) { $short_excerpt = substr( get_the_excerpt(), 0, 80 ); $excerpt = substr( $short_excerpt, 0, strrpos( $short_excerpt, ' ' ) ); $excerpt .= '[…]'; $html .= '<p>' . wp_kses_post( $excerpt ) . '</p>'; } $html .= '</li>';
More precisely, the following information will be displayed: a post title linking to the post itself, the post’s featured image, and its excerpt (if the given post has either of the last two). The excerpt is shortened to the last whole word before the 80th character, to avoid any word-breaks.
You can use this shortcode anywhere on your pages or posts, or you can add it to your chosen widget area. Below, we will explain how you can include this shortcode inside the sidebar of your theme. If you aren’t familiar with shortcodes and how to use them, we suggest taking a look at our article on custom shortcodes before continuing.
To insert our example code inside the sidebar, navigate to Appearance > Widgets. Then insert a Text widget inside the sidebar widget area of the theme you are currently using. Remember that the name of the widget area can differ from theme to theme. In our case, that widget area is called Main Sidebar. Insert [random-posts] to call the shortcode. And, if you want, you can add a title to the Text widget containing the shortcode.
Now that you have a better understanding of the shortcode, you can consider creating additional CSS code. In most cases, additional CSS will be needed to stylize the content, as it could be only partially styled by your current theme or have a default browser stylization. As we mentioned previously, you should create that CSS code yourself, since it should be made on a case-by-case basis. After putting yours together, insert it in Appearance > Customize > Additional CSS.
Below, you can see the CSS we created for displaying random posts in the Lekker WordPress theme.
ul.post-holder .post { margin-bottom: 30px !important; border-bottom: 2px dotted black; } ul.post-holder .post a{ color: red !important; } ul.post-holder .post a:hover{ color: #2e629c !important; } ul.post-holder .post img { margin-bottom: 10px; }
After inserting the shortcode and the CSS as described, we got the resulting random posts section (which you can see on the screenshot below).
Final Thoughts
Displaying random posts in suitable places on your website is a handy option that every blog should take advantage of. It can help funnel much-needed traffic to your older, but still relevant posts, as well as keep your readers engaged. While showing random posts isn’t a default WordPress feature, you can enable it quite easily. Simply follow the methods we outlined in this article and your readers will soon be spoiled for choice. Don’t forget to make sure that the random posts section you include matches the design of your website by adding some CSS code. Then sit back and reap all the benefits that the influx in website traffic will bring. And, if you feel like shaking things up later on, you can always show your most popular posts instead. As they have already proven popular with your readers, they are sure to draw in a crowd and give your page views a bump.