Display random post on a page with post permalink in URL

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.

Read More

Thanks

Related posts

Leave a Reply

3 comments

  1. 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».

  2. Try This …

    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.wpbold.com/displays-random-posts-in-a-page/

  3. <?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