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've got some code which creates a nice link to a random post - any way to amend it so that on a category page it selects a post from the current category?

thanks,

<?php
$randomPost = $wpdb->get_var("SELECT guid FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY rand() LIMIT 1");
echo '<a href="'.$randomPost.'">Random Post</a>';
?>
share|improve this question
add comment

1 Answer 1

I think it's better to use get_posts function. You can change the number of posts that you want. I set the category id if you're in a category page.

<?php
    rewind_posts() ;
    $args = array( 'numberposts' => 1, 'orderby' => 'rand') ;
    $exclude_posts = array() ;
    if ( have_posts() ) { 
        while ( have_posts() ) { the_post();
            $exclude_posts[] = get_the_ID() ;
        }
    }
    $args['exclude'] = $exclude_posts ;
    if( is_category() ) {
        $args['category'] = get_query_var('cat') ;
    }
    $rand_posts = get_posts( $args ) ;
    foreach( $rand_posts as $post ) {
        echo '<a href="' . get_permalink( $post->ID ) . '">Random Post</a>';
    }
    rewind_posts() ;
?>

I hope it helps you :-)

UPDATE Now exclude the posts showed in this page

share|improve this answer
    
Hi - thanks for this. I'm never going to need more than one post - it's literally a link to a random post. I also need it to dynamically recognise the post of the current category thats displaying - this doesn't seem to do that... sorry! –  JorgeLuisBorges Oct 19 '11 at 18:04
    
What do you mean with "I also need it to dynamically recognise the post of the current category thats displaying". Usually, there are more than one post displaying in the current category. –  Juan Ramón Oct 19 '11 at 18:07
    
I've just modified the first answer, excluding the post id's showed in the same page. –  Juan Ramón Oct 19 '11 at 18:22
    
sorry - typing in a hurry to leave the office - I meant recognise the current category - not the current post - my bad! –  JorgeLuisBorges Oct 20 '11 at 15:00
    
still doesn;t seem to grab only posts from the current category - it seems anything goes - also - the original thing I post was almost there - and seems simpler - i ther not a way to simply add in a variable to only pick from the current category? –  JorgeLuisBorges Oct 20 '11 at 15:01
show 1 more 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.