Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
30 Million+
Websites using our plugins
20+
Years of WordPress experience
3000+
WordPress tutorials
by experts

How to Display Random Posts in WordPress (Quick Tutorial)

Your WordPress blog probably has dozens of great older posts, but new visitors only ever see your most recent ones, while everything else remain buried in your archives.

Displaying random posts is an easy way to fix that. Every page load surfaces different content, which gives older posts fresh exposure and keeps visitors clicking around your site longer. You can even add a “Random Post” button that lets readers jump to a surprise article, classic StumbleUpon-style.

In this tutorial, we’ll show you how to display random posts in WordPress, plus how to redirect visitors to a random post with a single link.

Displaying random posts in WordPress

Simply use the quick links below to jump to the method you want to use:

How to Display Random Posts in WordPress

Looking for a fun way to keep visitors clicking around your site? You can easily add a list of random articles right into your sidebar, pages, or directly inside your blog posts.

While some tutorials may suggest adding custom code to your theme’s functions.php file, we recommend using WPCode, the free code snippets plugin for WordPress.

WPCode comes with smart code snippet validation to prevent common code errors from breaking your site. It also makes your customizations future-proof, meaning you can update or switch to a different theme without worrying about losing all custom code functions.

First, you need to install and activate the free WPCode plugin. For detailed instructions, please see our beginner’s guide on how to install a WordPress plugin.

Upon plugin activation, head over to the Code Snippets » + Add Snippet page from the WordPress admin sidebar.

Once you’re there, click the ‘+ Add Custom Snippet’ button under the ‘Add Your Custom Code (New Snippet)’ option.

Choose'Add Your Custom Code (New Snippet)' option

Next, select ‘PHP Snippet’ as the code type.

You will then be taken to the ‘Create Custom Snippet’ page, where you can start by typing a name for the code snippet.

This title is just for your reference and won’t appear anywhere on your site.

Creating a custom code snippet in WordPress

Next, simply copy and paste the following code into the ‘Code Preview’ box:

<?php
$number_of_posts = 5; // Change this to the number of random posts you want to display.
$title = 'You might also like:'; // This is the title that will be displayed above the list of posts.
$current_post_id = get_the_ID();
$args = array(
	'post_type'      => 'post',
	'orderby'        => 'rand',
	'posts_per_page' => $number_of_posts,
	'post__not_in'   => array( $current_post_id ),
);
$random_posts = new WP_Query( $args );
if ( $random_posts->have_posts() ) {
	echo '<h3>' . esc_html( $title ) . '</h3>';
	echo '<ul>';
	while ( $random_posts->have_posts() ) {
		$random_posts->the_post();
		echo '<li><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></li>';
	}
	echo '</ul>';
}
wp_reset_postdata();

This snippet shows 5 random posts wherever you place its shortcode, and it automatically leaves out the post the visitor is already reading.

To show a different number, change the $number_of_posts value at the top of the snippet. The $title line controls the ‘You might also like:’ heading that appears above the list, so edit that text or set it to '' if you’d rather not have a heading at all.

After that, you’ll need to save the snippet in order to generate a unique shortcode, so give the ‘Save Snippet’ button a click.

How to save a code snippet to your WordPress blog or website

After that, scroll to the ‘Insertion’ section and choose the ‘Shortcode’ option.

You’ll now see the shortcode that WPCode generated automatically. Click its ‘Copy’ button as you’ll be using this shortcode in the next step.

How to copy a shortcode to your WordPress blog or website

Finally, scroll back to the top and toggle the ‘Inactive’ switch to ‘Active’.

After that, simply click the ‘Update’ button to store your changes.

Publishing a custom code snippet to your WordPress website

After saving the code snippet, you can display random posts on your site using the shortcode we copied earlier.

Adding a shortcode block to your WordPress website

For more details on how to do this, see our guide on how to add WordPress shortcodes.

If the same random posts keep showing up instead of changing, then it is usually your page cache serving a saved copy of the page. Start by clearing your cache and reloading the page.

If they still don’t change, then exclude that page from your caching plugin’s full-page cache.

How to Redirect Users to a Random Post (With a Plugin)

While showing a list of random posts works great in your sidebar or at the end of an article, it still asks visitors to scan the titles and pick one. In the earlier days of web, we really enjoyed using Stumbleupon which made it easy to discover new content with a click of a button.

You can add similar functionality on your website where instead of displaying a list, you create a ‘Random Post’ button or ‘Surprise Me’ link that instantly takes visitors to a random article on your site. It’s a fun way to encourage exploring, and it works especially well on your 404 page or in your navigation menu.

We recommend using the free Random Post Plugin. It works by adding a ?redirect_to=random URL parameter to your site.

Simply install and activate the plugin, then add a link to your navigation menu, sidebar widget, button, or anywhere else on your site. A visitor can then click it to visit a random post.

To build your own link, you will need to replace www.example.com with your own domain name.

Here are the variations you can use:

  • www.example.com/?redirect_to=random&each_once=rewind. Ensures visitors don’t see the same post twice. This link automatically resets once they’ve seen every post on your site.
  • www.example.com/?redirect_to=random&count=10. Only shows random posts from your 10 most recently published articles.
  • www.example.com/?redirect_to=random&after=1 month ago. Only shows random posts that were published within the last month.
  • &cache=120. Add this to the very end of your URL to temporarily save (cache) the result for 120 seconds. This helps your WordPress site load faster.

For example, you can create a button that shows a random post, selected from your 20 most recent posts:

Adding a random posts link to WordPress

If you prefer a ready-made ‘Random Post’ button, then the plugin also includes a handy shortcode.

You can easily add the [redirect_to_post_button] shortcode to any post, page, or widget area. If you need help, check out our beginner’s guide on how to add a shortcode in WordPress.

Creating a&apos;Random Posts&apos; button

How to Redirect Users to a Random Post in WordPress (With Code)

If you’d rather not install another single-purpose plugin, then you can set up the same ‘Random Post’ redirect with a code snippet instead.

This snippet creates a brand new URL on your website, which will look something like example.com/random.

This won’t mess with any of your existing pages, and it won’t affect the readers who are browsing your posts. The redirect only happens when someone manually visits that new /random address, like when they click a ‘Random Post’ button or menu link you’ve set up.

So, whenever a reader visits example.com/random, WordPress will automatically grab one of your published posts completely at random and redirect them straight to it.

To keep your site safe, we’ll add the code using the WPCode plugin we set up earlier. This makes sure that a single mistyped character won’t break your website or lock you out of your admin area.

You can simply paste it as a new PHP snippet in WPCode, following the same steps we covered earlier:

<?php
function wpb_random_post_rewrite() {
    add_rewrite_rule( '^random/?$', 'index.php?random_redirect=1', 'top' );
}
add_action( 'init', 'wpb_random_post_rewrite' );
function wpb_random_post_query_var( $vars ) {
    $vars[] = 'random_redirect';
    return $vars;
}
add_filter( 'query_vars', 'wpb_random_post_query_var' );
function wpb_do_random_post_redirect() {
    if ( get_query_var( 'random_redirect' ) ) {
        $random = get_posts( array(
            'post_type'      => 'post',
            'orderby'        => 'rand',
            'posts_per_page' => 1,
        ) );
        if ( $random ) {
            wp_redirect( get_permalink( $random[0]->ID ), 307 );
            exit;
        }
    }
}
add_action( 'template_redirect', 'wpb_do_random_post_redirect' );

You may have noticed that this snippet uses a 307 redirect, which tells the browser that the destination is temporary.

This is because web browsers cache permanent 301 redirects to speed up loading times. As a result, the browser would keep sending a visitor to the same post, breaking the randomization entirely.

Once you’ve saved and activated the snippet, simply go to Settings » Permalinks in your WordPress dashboard and click the ‘Save Changes’ button.

This quick step is known as ‘flushing your permalinks.’ It forces WordPress to refresh its link structure so it can instantly recognize your brand new /random URL.

If you’re using a WordPress caching plugin to speed up your site, be sure to add /random to its list of excluded URLs. This makes sure the redirect runs fresh every single time instead of serving up a cached page to your visitors.

Your random redirect is now ready to use. You can point any link to example.com/random, whether that’s a button, a navigation menu item, a sidebar widget, or a text link inside a post.

Just remember to replace example.com with your own domain name.

We hope this article helped you learn how to display random posts in WordPress. You may also want to see our beginner’s guide on how to easily re-order posts in WordPress and our tutorial on creating a private post in WordPress.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here's our editorial process.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!

Reader Interactions

35 CommentsLeave a Reply

  1. I’ve tried several methods to display random posts but none of them worked well like this custom query method. This tutorial is easy to understand and I love how you provided examples and code snippets to help illustrate the process. Your expertise has saved me so much time and frustration. Keep sharing your knowledge with us!

  2. As I understand, the code is without featured images of posts. Is any options with code to display posts with featured images too?

      • Thank you for the advice. Yes, that works for me. I use Elementor and occasionally Seed Prod. Since I never use Gutenberg, this option never occurred to me. I simply didn’t know that Gutenberg had such a block. Thanks for the tip.

  3. My sticky posts always showing up in my random posts. Is there a way to exclude sticky posts from this code?

    • To achieve that we would recommend using the plugin from the second method rather than tweaking the code.

      Admin

  4. Is there an easy way to cache the results for a certain period of time instead of randomizing every time? Maybe like refresh once every 24hrs to reduce lessen the load on DB calls every time?

    • For that functionality, you would want to check with the plugin’s support for if it is available.

      Admin

  5. Please, i tried adding the shortcode on a specific position on my website not inside the post in PHP but the Random post section did not display but only show my text “[wpb-random-posts]”.

    What should i do?

    • When using the block editor you would want to ensure you’re adding it using a shortcode block.

      Admin

  6. Thanks the code works just fine. I changed the first page in my wordpress site to index.html, what do I need to run [wpb-random-posts] on my html page? My English is a bit weak, I hope you understand me.

    • You would need the page to be a WordPress page for a WordPress shortcode to work.

      Admin

  7. How would you go about styling this? I’m getting confused as to how I would control the design of this, i’ve never worked with styling PHP.

    • It would depend on the styling you’re wanting to add for what needs to be done. You can add a class in the html code to give you something to target.

      Admin

  8. Thanks for the helpful article.

    I have a question — my Wordpress site pages include a sidebar with a random post (excerpts) widget.

    A problem is that Google indexes the pages and ‘sees’ the random post excerpts as content for the page. So in Google search, a page can show up as matching a search term only because one of the random post excerpts on the page matched the term (not the main content of page).

    But, when a user clicks on the link in Google search results they will see the page with a different set of random post excerpts in the sidebar — not the post excerpt with matching text. So it looks to them like a bad search.

    Ideally i’d like to exclude the random post excerpts from Google index ie hide them from Google, but that doesn’t look possible (?).

    If you have any suggestions I’d appreciate it! Thanks.

  9. Thanks a million for sharing this. I used another plugin for random post that no longer works. Then I find your site and have installed the plugin. It works like a charm.

  10. Hi, and thanks for this helpful tutorial!
    Can you tell me what would be the piece of code to add to display random posts that are in a specific category? My theme doesn’t display a sidebar so I can’t use the plugin and it already has a random posts display under each article, but posts from all categories are included and displayed then. I tried to go check the theme code and add ‘post_category’ => ‘name-of-the-category’, but it doesn’t work. Any idea?

  11. Hi! I just want to ask what if i want to change random post every week or any given time. For example, i display a set of random post, it will not change until 7days or any given time. Thanks!

  12. Thanks a ton, I was able to display random posts. I changed the no of posts to 1 to display 1 random post. Is there a better way to do it?
    I would also like to find out how I can use a variable instead of post type and enter one where I place the short code eg – [wpb-random-posts(‘post’)].
    How can I achieve this ??

  13. Setting posts to orderly => ‘rand’ is a half-measure. Sure, the post displays ‘randomly’, but like DI SEKITAR mentioned above, what use is displaying one random post if it’s going to be the same random post every time someone visits the site?

  14. Sorry, But the string was not working and i just make the string global and it works fine now.

    global $string;

  15. Thanks for this great tutorial. Is there some way I can get the shortcode and then display the random posts beneath the content in a page instead of the sidebar??

  16. JAYKAY

    To exclude the current post add

    ‘post__not_in’ => array(get_the_id())

    to the query.

    So your args will now be:

    $args = array(
    ‘post_type’ => ‘post’,
    ‘orderby’ => ‘rand’,
    ‘posts_per_page’ => 5,
    ‘post__not_in’ => array(get_the_id()),
    );

  17. really cool information,
    I tried used plugin that you mention, but i have big question.

    How to make random post different for every visitor or device that visiting my site?

    because i try visit my site using other notebook and smartphone, but the random post from those 2 device is same.

  18. Hi,

    Advanced Random Posts Widget is a really good plugin, but i have a problem.
    How could you exclude the current/active post when you display a random post ?
    Is it possible to fix this ?

    The problem is the same with the method 2 code.

  19. thanks for this. i was always thinking about this, Since by default the latest post are visible on the home page itself. Thanks for this will definetely use this plugin

Leave A Reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.