An archive page is nothing more than a page with links to your blog posts ordered by date, category, etc. In this tutorial we’re going to list all the blog posts in our blog, ordered by date in a hierarchical way. Something like this:
-
May 2008
- 25 - Lorem ipsum
- 12 - Dolor sit amet
-
April 2008
- 22 - Adipiscing elit
- 18 - Consectetur
- 3 - Ipsum amet
- …
Cool, eh! Let’s go…
The page
First create a new php file and type this at the very beginning:
<?php /* Template Name: Hierarchical Archives */ ?>
This will help us identify the template when we create the archives page in the WordPress back-end.
Now, let’s enter the basic page code. You may want to open the page.php file of your theme, and copy the structure. I’ll be using the default “kubrick” theme structure for this tutorial:
<?php get_header(); ?> <div id="content" class="widecolumn"> <!--Here is where our code will go--> </div> <?php get_footer(); ?>
The code
Ok and now this is the code that will print the actual list of posts:
<?php // Declare some helper vars $previous_year = $year = 0; $previous_month = $month = 0; $ul_open = false; // Get the posts $myposts = get_posts('numberposts=0&orderby=post_date&order=DESC'); ?> <?php foreach($myposts as $post) : ?> <?php // Setup the post variables setup_postdata($post); $year = mysql2date('Y', $post->post_date); $month = mysql2date('n', $post->post_date); $day = mysql2date('j', $post->post_date); ?> <?php if($year != $previous_year || $month != $previous_month) : ?> <?php if($ul_open == true) : ?> </ul> <?php endif; ?> <h3><?php the_time('F Y'); ?></h3> <ul class="month_archive"> <?php $ul_open = true; ?> <?php endif; ?> <?php $previous_year = $year; $previous_month = $month; ?> <li><span class="the_day"><?php the_time('j'); ?></span> <span class="the_article"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></span></li> <?php endforeach; ?>
How does this work? Well… it’s a little hard to explain. Basically, we’re using the get_posts() function to get all the posts (numberposts=0 means all of them), ordered by date (orderby=post_date) in descending order (order=DESC). Then, we’re looping through every last one of them, comparing it’s published month and year to the previous one and echoing the year and the month accordingly.
Wrapping up
That’s basically it. Now save this file and upload it to your template directory (/wp-content/themes/your_theme). Then create a new page in the WordPress back-end, selecting “Hierarchical Archives” in the page template drop-down menu. And you’re done.
Hope you liked the pseudo-tutorial ;-).
On WordPress 2.6, it only shows the last month.
Or maybe it displays only number of posts that you set in Options -> Reading.
I just have the last 5 posts… as I set to display on front page.
(See http://www.designgrafik.net/archives/ )
Forget it. I’m using another PHP script now…