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 did some reasearch but couldn't find a way to do it. Just to be clear I don't want to show a widget list of random posts on the sidebar. I want the ability for reader to click on a link that says "Random Post" and it will take them to a random post from my archive. How would I do it? I am php noob, so working code snippet would be much appreciated.

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

Looks like you're after Random Post Link.

For completeness here's some code (the plug-in is a little more involved as it stores as a cookie previous random posts, so they don't twice).

(The following is based on the above plug-in by Scribu)

//Create random url - use this where you want the link to be displayed
$url = add_query_arg( 'wpse82608', 'random', trailingslashit( get_bloginfo( 'url' ) ) );
printf( '<a href="%s" > Random Post </a>', $url );

Then interpet the random url (this can go in a plug-in or, if you must, your theme's functions.php)

add_action('init', 'wpse82608_random_post_redirect' );
function wpse82608_random_post_redirect(){

    if( empty( $_GET['wpse82608'] ) || 'random' != $_GET['wpse82608'] )
        return;

    //Get a random post
    $posts = get_posts( array(
        'orderby' => 'rand',
        'showposts' => 1,
     ));

    //If no posts founds - redirect to site.
    if ( empty($posts) ){
        wp_redirect( get_bloginfo( 'url' ) );
        exit();
    }

    //Get the random post's ID
    $id = $posts[0]->ID;

    //Redirect to post
    wp_redirect( get_permalink( $id ) );
    exit();
}

This is untested.

share|improve this answer
    
I tried the plugin and it did the rick. Thanks. :) –  bran Jan 22 '13 at 12:24
add comment

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.