Support » Themes and Templates » Recent Posts in Random Order

  • Resolved andy120

    (@andy120)


    I’m trying to put a list of recent posts in the sidebar of my blog, but I want them to be in random order. So the most recent 20 posts, but not ordered by date.

    <?php $topStoriesList = new WP_Query('showposts=20'); ?>
    <?php while ($topStoriesList->have_posts()) : $topStoriesList->the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
    <?php endwhile; ?>

    This is what I have, but if I change it to “&orderby=rand” it randomizes the posts it grabs so they aren’t the 20 most recent. Help? Thanks.

Viewing 5 replies - 1 through 5 (of 5 total)
  • try adding the orderby=rand property like:

    <?php $topStoriesList = new WP_Query('showposts=20&orderby=rand'); ?>
    <?php while ($topStoriesList->have_posts()) : $topStoriesList->the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
    <?php endwhile; ?>
    Thread Starter andy120

    (@andy120)

    I just copy/pasted that and tried it, but the results were completely random regardless of whether they were the most recent 20 or not.

    You could probably use shuffle($post-array);

    But not too sure on the name of the array of which retrieved posts from the query are stored in.

    EDIT: Try adding shuffle($posts) after the if have_posts part of your loop

    okay how about this. maybe a little long winded but seems to do the trick.

    <?php
    $number = "4";
    $posts = "SELECT * from $wpdb->posts WHERE post_type='post' ORDER BY post_date DESC LIMIT $number";
    $postX = array();
    $postresult = mysql_query($posts) or die(mysql_error());
    
    while ($row = mysql_fetch_array($postresult)) {
    $postX[] = $row[0];
    }
    //$ids = shuffle($postX);
    $ids = implode(',', $postX);
    //echo $ids;
    
    ?>
    <?php
    $args = array(
    	'showposts'=> $number,
    	'post__in' => explode(',', $ids),
    	'orderby' => 'rand'
      );
    query_posts($args);
     ?>
    <?php while (have_posts()) : the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
    <?php endwhile; ?>

    See at the top of the code where it has $number = "4";? change the “4” to be the number you want to show.

    Thread Starter andy120

    (@andy120)

    tugbucket,

    It works perfectly. Much appreciated!!

    Thanks.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Recent Posts in Random Order’ is closed to new replies.