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(); ?>
create a page template, and use the following code to get a random post:
then in a page, just use:
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:Use
mydomain.com/random/
as yourhref
for your button that leads to the random post.Thanks everyone who contributed for your help…
Cheers!
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
All you need to do is append it with ?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
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()
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!
source: http://www.yengkokpam.com/displays-random-posts-in-a-page/
Check This