Controlling Archives

Posted: 23rd Mar 2008, in: Snippets - Older Post - Newer Post

If you want to display a list of archive links in WordPress the way you do it is with the template tag: wp_get_archives. But what if you want a little more control?

Unlike bookmarks and categories there doesn’t seem to be a quick and easy way to retrieve an array of archive links as an array for later use. So what do you do if you want a list of archives exactly the same as that generated from the code below, but you want to insert something else into that list?

<?php wp_get_archives(‘type=monthly&limit=12′); ?>

WordPress has three functions that make it much easier to generate lists of archives manually:

  • get_day_link( $day , $month , $year );
  • get_month_link( $month , $year );
  • get_year_link( $year );

These functions each return the appropriate permalink for the date provided to them. All you need to do is to calculate the dates you want to include.

The code snippet below shows the links for this and the previous 11 months and adds a class (selected) to the list item if the page it is displayed on is an archive from the month and year selected.

for ($i = 0; $i < 12; $i++){
 
	$the_date = mktime(0, 0, 0, date("m")-$i, date("d"),   date("Y"));
	$year = date("Y", $the_date );
	$month = date("m", $the_date);
	$selected_class = ;
 
	if ( $wp_query->get(‘monthnum’) == $month && $wp_query->get(‘year’) == $year ){
		$selected_class = ‘ class="selected" ‘;
	}
 
	echo ‘<li’.$selected_class.‘>’;
	echo ‘<a href="’.get_month_link($year, $month).‘">’.date(‘F Y’,$the_date).‘</a>’;
	echo ‘</li>’;
 
}

This can be amended in a variety of ways to add extra functionality to a theme, including paging, listing posts inline, and even combining with Javascript to produce a dynamic menu of years, months and days.

 

Comments

Other blogs writing about this

  1. WordPress and Blogger News and Tutorials - Blog Tipz (http://blogtipz.com/wordpress-and-blogger-news-and-tutorials/) 26th 03 2008 at 4:19 am

    [...] Controlling Archives (WP-Fun) [...]

     

Leave a Reply

I am currently testing a comment link policy which means commenters do not get a link. There is a poll, and open comments for feedback on the comment policy page.

Please note. I am currently using an experimental antispam technique on this blog. If you run into problems please let me know using the Get in Touch link at the top of the page. Thanks, Andy.

Subscribe without commenting

Feed Icon - Get fed with RSS