• Hi. Based on the get_posts() documentation on the Codex, I’m trying to create a simple sidebar widget to list 5 random posts from the blog’s archives. My code is as follows:

    function widget_from_the_archives($args) {
      extract($args);
    ?>
      <?php echo $before_widget; ?>
      <?php echo $before_title . "From the archives" . $after_title; ?>
      <ul>
        <?php
          $rand_posts = get_posts("numberposts=5&orderby=rand");
          foreach( $rand_posts as $post ) :
            setup_postdata($post);
        ?>
          <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endforeach; ?>
        </ul>
      <?php echo $after_widget; ?>
    <?php
    }

    Problem is, this code selects the same post 5 times. Am I doing something wrong? The code seems pretty straightforward, but it’s not working for me. Please let me know if I’m missing something obvious.

    Thanks in advance,
    Richa Avasthi

  • The topic ‘Random posts in sidebar’ is closed to new replies.