Random post query - include all posts of a random year (5 posts)

  1. stemie
    Posted 3 years ago #

    Im trying to create a query that shows all the posts from a random year. So when a visitor comes to the page they get a random year with all the posts from that year.

    Im creating an historic site with a post for each month of the year so each random year will always have 12 posts. Eg each year 1986, 1987 etc. has 12 posts.

  2. Chouby
    Posted 3 years ago #

    You can do something like this:
    query_posts('year='.rand(1986, 2011));

  3. stemie
    Posted 3 years ago #

    Thanks for the reply

    I tried a basic loop just to see if it works but I get an error

    <?php query_posts ('year='.rand(1986, 2011)); ?>
    <?php while (have_posts()) : the_post(); ?>
    <?php the_title(); ?>
    <?php endwhile; ?>
    <?php endif; ?>

    Parse error: syntax error, unexpected ';', expecting T_STRING or T_VARIABLE or '$' in /home/content/30/8250330/html/racingmuseum.co.za/site/wp-content/themes/toolbox/random-year.php on line 58

    Line 58 being the first line, query.


  4. stemie
    Posted 3 years ago #

    Ok I think I got it now, was some charater changes when I copy pasted it.

    Thanks for your help seems like an easy solution.

    // The Query
    query_posts ('year=' . rand(1986, 2011));
    // The Loop
    while ( have_posts() ) : the_post();
    	echo '<li>';
    	echo '</li>';
    // Reset Query
  5. Michael
    Part-Time Forum Moderator
    Posted 3 years ago #


    query_posts ('year=' . rand(1986, date('Y')-1));

    should automatically expand this to the last full year, excluding the current year (untested).


Topic Closed

This topic has been closed to new replies.

About this Topic