WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the settings so only one post (which is by default the most recent) displays with index.php

my current working code

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

How could I change to code to display a random post from any category/date?

It just needs to be one post if that makes a difference.

many thanks

share|improve this question
up vote 1 down vote accepted

Place the following code in your theme functions.php file.

function one_random_post_on_home_page( $query )
    if ( ! ( $query->is_home() && $query->is_main_query() ) )

    $query->set( 'orderby ', 'rand' );
    $query->set( 'posts_per_page', 1 );

add_action( 'pre_get_posts', 'one_random_post_on_home_page' );

I'm assuming when you say index.php you mean your blogs home page. The index.php file in your theme can be used for many other areas of your website so making any alterations in that file might have undesired effects else where.

share|improve this answer
yes sorry, i did mean theme index. – bracketboy Aug 24 '12 at 14:51
is this code more reliable than: <?php global $query_string; query_posts( $query_string . '&orderby=rand' ); ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> – bracketboy Aug 24 '12 at 14:52
@bracketboy - using query_posts() for what you have asked for is bad. You can read more here: developer.wordpress.com/2012/05/14/… – Brady Aug 24 '12 at 15:27

Try posting this code above your current code:

<?php query_posts(array('orderby' => 'rand', 'showposts' => 1)); ?>
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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