YC Year Archives

In traditional Minmatar fashion, I’ve been tinkering and come up with more useful little tidbits for people to mull over and use in their own blogs.

And in the tradition of my former corporation, Re-Awakened Technologies Inc. it’s based on something that looked interesting; so I nicked it.

First of all, what we’re trying to achieve here is a list of links to yearly archives on a blog. Except we only want a list of years when a post was made in said year, and we want it to output the ‘YC’ year, not the literal, real-world year.

As a disclaimer: this is for WordPress blogs/sites, but you can probably adapt it accordingly for other types.

function minmatarts_get_archives() {
  global $wpdb;
  // Select the years that have posts in the database
  $query = "SELECT YEAR(post_date) AS `year` FROM $wpdb->posts WHERE `post_type` = 'post' AND `post_status` = 'publish' GROUP BY `year` ORDER BY `year` DESC";
  $ycresults = $wpdb->get_results($query);
  $years = array();
  if ($ycresults) {
    echo '<ul>';
    // As long as there were results (which there should be), do the following for each year
    foreach ( (array)$ycresults as $ycresult ) {
      array_push($years, $ycresult->year);
      // Format the year to YC standard
      $year = $ycresult->year - 1898;
      //Output the result with a nice title on the link
      echo '<li>';
      echo '<a href="'.  get_site_url().'/'.$ycresult->year.'" title="View all posts from YC'.$year.' ('.$ycresult->year.')">YC'.$year.'</a>';
      echo '</li>';
    }
    echo '</ul>';
  }
}

You want to drop this into your functions.php file. Then you can call it somewhere in your template like this:

<div class="annual-archives">
  <?php minmatarts_get_archives(); ?>
</div>

And that’s a quick and dirty way of getting a list of, and links to, all of the years in which you have posted entries.

Comments for this Post

Leave a Reply

Your email address will not be published. Required fields are marked *