16

How do I get a random post in Wordpress?

I would like to display a button on a page that, when pressed, goes to a random post from the blog. I don't want a random post to be displayed on the page, I just want a link that leads to that post. I tried searching for a code on Google and here at stackoverflow but no success.

Thanks...

UPDATE:

Here is my template code:

<?php /*Template Name: Random*/ ?>

<?php get_header(); ?>

<nav><?php wp_nav_menu(array('menu' => 'Main Nav Menu')); ?></nav>

<div id="main-content-archive">

<div class="grey-text">Random post</div>

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

        <?php if (have_posts()) : while ( $the_query->have_posts() ) : $the_query->the_post();
        echo '<li>';
        the_title();
        echo '</li>';
        ?>

<?php endwhile; ?>

<?php else : ?>

    <h2>Not Found</h2>

<?php endif; ?> 

</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
4
  • Perhaps this could help you: random post plugin Dec 29, 2011 at 19:22
  • Thanks but I was hoping for a simple code. This plugin doesn't allow customization of the link in the sense that I can replace the list of recent posts with a button. Any other idea?
    – rlab
    Dec 29, 2011 at 19:44
  • @rlesko a) don't use variables that could easily by globalized by core - don't use "$query", "$post" etc... Instead use e.g. $myQuery or something like that...
    – jave.web
    Jan 31, 2017 at 17:40
  • @rlesko b) You have bugged naming - you are setting "$query" variable, though you are asking if(have_posts()) - that is asking the MAIN query, you should have if($myQuery->have_posts()), same goes for the rest of ->have_posts() and ->the_post(), honestly, I am surprised your code did not throw any error on your head :-)
    – jave.web
    Jan 31, 2017 at 17:42

5 Answers 5

25

create a page template, and use the following code to get a random post:

//Create WordPress Query with 'orderby' set to 'rand' (Random)
$the_query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );
// output the random post
while ( $the_query->have_posts() ) : $the_query->the_post();
    echo '<li>';
    the_title();
    echo '</li>';
endwhile;

// Reset Post Data
wp_reset_postdata();

then in a page, just use:

<a href="the link to the page">see a random post</a>
3
  • 1
    It doesn't seem to be working. Please check out the update in the question.
    – rlab
    Dec 30, 2011 at 20:03
  • @rlesko Could that be a sticky post issue? You could try setting ignore_sticky_posts argument to false :) Otherwise you have some major bugs in your code - I've commented on your question ;)
    – jave.web
    Jan 31, 2017 at 17:48
  • 1
    Not a sticky post issue, just not quite understanding how this query works. The orderby "rand" will just change the order of the posts that have been queried, and telling it posts_per_page of 1 only brings back a single post. So it returns one post, then randomizes the order (aka always the same post).
    – clark
    Jul 21, 2017 at 17:22
7

I found this post which gave me desired results...

Here's a solution copy/pasted from the wpbeginner blog post. No copyright infringement intended.

Just add the following code to the functions.php file:

add_action('init','random_add_rewrite');
function random_add_rewrite() {
   global $wp;
   $wp->add_query_var('random');
   add_rewrite_rule('random/?$', 'index.php?random=1', 'top');
}

add_action('template_redirect','random_template');
function random_template() {
   if (get_query_var('random') == 1) {
           $posts = get_posts('post_type=post&orderby=rand&numberposts=1');
           foreach($posts as $post) {
                   $link = get_permalink($post);
           }
           wp_redirect($link,307);
           exit;
   }
}

Use mydomain.com/random/ as your href for your button that leads to the random post.

Thanks everyone who contributed for your help...

Cheers!

2
  • This is an interesting solution, though wrong by design - you should rather repair your original code as this brings unnecessary redirect ;)
    – jave.web
    Jan 31, 2017 at 17:44
  • 1
    Your answer implements the solution provided by @bingjie2680 for finding a random wordpress post even if the user didn't write the whole functionality for you.
    – FroboZ
    Jul 10, 2020 at 7:49
4

I find it is more useful to have a URL that will redirect to a random post that you can use as link in sidebar or in menus. If it is a single WP site and even on wp.com it's really easy, for a blog at

http://mygroovywpsite.me/

All you need to do is append it with ?random

http://mygroovywpsite.me/?random

I found this did not work (nor the wp_beginner code above) on subsites in my multisite installation, either approach just loaded the home page. Maybe I had some funky cache issues. The way I do this on many sites is a few more steps w/o plugins.

First make a Page in your site called "Random" / with the slug "random" -- it does not need any content in it

Then create a page-random.php template

<?php
/*
Random Post Picker
Use on page to send viewer to random post optionally mod query
*/

// set arguments for WP_Query on published posts to get 1 at random
$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 1,
    'orderby' => 'rand'
);

// It's time! Go someplace random
$my_random_post = new WP_Query ( $args );

while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();

  // redirect to the random post
  wp_redirect ( get_permalink () );
  exit;
}
?>

Then you get the re-direct for any link on your blog ...../random w/o any wrestling with .htaccess

I've done it this way because I've had to modify the query, sometimes for custom post type, sometimes to restrict to category, etc.

I only had one site that was a problem because the hosting suppressed the use of mySQL queries with ORDER BY RAND()

0
4

Another Simple solution to display Random Post

1.First a create a custom page template. Name it as random post or a name of your choice!

2.Open the page and remove the default wp loop and Paste the code below

3.To change the no of post change the number ‘1’ to your choice!

 <?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post(); ?>
 
<h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>
 
<?php the_content(); ?>
 
<?php endwhile;

endif; ?>

source: http://www.yengkokpam.com/displays-random-posts-in-a-page/

1
  • 1
    Please check the URL, It's a porn website. Nov 3, 2020 at 5:23
1

Check This

<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
   <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.