Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have seen many snippets to display random post/posts on a page. Most of them provide a function or wp_query code to be directly placed where it is required. In the end they tell to create a template random.php and page with name RANDOM. So, when one wants to access that page, they can look for a link pointing as http://domain.com/random/. And every time, I find the same URL -->http://domain.com/random/. What I want is to display the URL of the post i.e permalink in the address bar, whenever one clicks on random page link e.g post-permalink. I use this piece of code.

    query_posts(array(
    'showposts' => 1,
    'orderby' => 'rand',
    ));
if (have_posts()) : while (have_posts()) : the_post();

I don't know much about using 'base' and 'format' arguments in the array, they might serve purpose.

Thanks

share|improve this question
1  
Your question is unclear to me. can you please elaborate? –  Rohit Pande Jan 10 '13 at 9:36
2  
Nevermind Rohit, I did it! –  10wtaylor Jan 10 '13 at 12:14

2 Answers 2

up vote 1 down vote accepted

What you are asking is how to redirect the visitor to a random post. Here you go:

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

query_posts(
    array(
        'showposts' => 1,
        'orderby' => 'rand',
    )
);

if (have_posts()) : while (have_posts()) : the_post();

header( 'Location: ' . get_the_permalink() , false , 303 );

The syntax is

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

... and the 303 status code denominates «See other».

share|improve this answer
<?php
/*
Template Name: Random Post
*/
get_header(); ?>
<section>
<div class="inner">
    <?php
        query_posts(array('orderby' => 'rand', 'showposts' => 1));
        if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-content">
                            <?php the_content(); ?>
            </div>
</div>
        <?php endwhile; ?>
    </div>
</section>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

Hope this code will help you to fix your problem

share|improve this answer
    
Please read the question more carefully. The OP is aware of this solution but is looking for a different one. –  s_ha_dum May 6 at 10:54

Your Answer

 
discard

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.