display random post in current category? (3 posts)

  1. qzha017
    Posted 3 years ago #

    Hi everyone I am using the twenty ten theme and all my posts are ordered by the newest one at top, how can I make it random? So when I click into my categories on home page it will show all post of that category random.

    I know the
    <?php query_posts('posts_per_page=99&order=rand&cat=25&post_status=publish,future');?>

    But because I have alot of categories I dont want to make a php file for every category and query random posts for a specific category in a specific category.php. And if I only put in order=rand, then it will show all random post (from all categories).

    I can't find anything regarding to order of post in my loop-category.php

    maybe I need to add the above code within my loop so it calls for random post within the current category?

    Hope someone can help me out
    Thanks alot in advance

  2. Tara
    Volunteer Moderator
    Posted 3 years ago #

    see if this snippet will do what you intend (not tested):

        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() ;
  3. qzha017
    Posted 3 years ago #

    Thank you can you tell me where do I put the code?
    Which file (I assume the loop-category), and which part in that file?

    thank you T-P

Topic Closed

This topic has been closed to new replies.

About this Topic