WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. stemie
    Member
    Posted 2 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
    Member
    Posted 2 years ago #

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

  3. stemie
    Member
    Posted 2 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.

    http://racingmuseum.co.za/site/random-year/

  4. stemie
    Member
    Posted 2 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.

    <?php
    
    // The Query
    query_posts ('year=' . rand(1986, 2011));
    
    // The Loop
    while ( have_posts() ) : the_post();
    	echo '<li>';
    	the_title();
    	echo '</li>';
    endwhile;
    
    // Reset Query
    wp_reset_query();
    
    ?>
  5. alchymyth
    Forum Moderator
    Posted 2 years ago #

    using:

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

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

    http://php.net/manual/en/function.date.php

Topic Closed

This topic has been closed to new replies.

About this Topic