WordPress.org

Support

Support » Plugins and Hacks » Hacks » display random post in current category?

display random post in current category?

  • 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

Viewing 2 replies - 1 through 2 (of 2 total)
  • Tara

    @t-p

    Volunteer Moderator

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

    <?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() ;
    ?>

    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
    Alex

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘display random post in current category?’ is closed to new replies.