- Projects -     - Mouldy Soups -     - Mouldy Bread -     - Contact -     - Links -     - Cheap Plastic Stuff -     - Photo Gallery -

Mr Mist’s Blog

It’s very sensible

Posts Tagged with ‘filters’

Filtering archives

Sunday, January 11th, 2009

So today I took a look at the massive list of archive links that has been steadily growing down the right-hand side of my blog since 2001. I like to have a list of links rather than the drop-down menu style, but even I had to admit that 8 years of monthly archives was getting a bit much.

So I’ve done a quick re-design. The current year’s worth of archives are now linked monthly, with the rest being links to the yearly pages, from which each year is linked monthly.

Well, I say “quick”, but it has taken a few hours I think. Firstly I had to figure out how to get a new widget on the side-bar, as I had forgotten. Then I had to figure out how to get the wp_get_archives function to do yearly and monthly output – again, not too difficult, as that was in the Codex.

But then I wanted the yearly list to miss out the current year. Hmm. How to do that? There’s no parameter for that. After a bit of digging around through the WordPress code, I learnt that you have to use a filter. The code for my filters eventually ended up looking like this -

function mist_thisyear_getarchives_where ($sql) {
global $mist_time;
$post = $posts[0];
if (is_year()) {
if (!isset($mist_time)) {
$mist_time = get_the_time('Y');
}
$sql=$sql . ' AND YEAR(post_date) = ' . $mist_time;
} else {
$sql=$sql . ' AND YEAR(post_date) = YEAR (CURRENT_DATE) ';
}
return $sql;
}

function mist_oldyears_getarchives_where ($sql) {
global $mist_time;
if (is_year()) {
if (!isset($mist_time)) {
$mist_time = get_the_time('Y');
}
$sql=$sql . ' AND YEAR(post_date) != ' . $mist_time;
} else {
$sql=$sql . ' AND YEAR(post_date) < YEAR (CURRENT_DATE) ';
}
return $sql;
}

And I then call the wp_get_archives function like this -


add_filter ('getarchives_where','mist_oldyears_getarchives_where');
wp_get_archives('type=yearly');
remove_filter ('getarchives_where','mist_oldyears_getarchives_where');

The various filters and bits of conditional code let me have different archive lists on the Archive and other pages. The strange bits around get_the_time are a hack, because otherwise the variable doesn’t seem to be quite right. Instead I have to set $mist_time in my Archive template, so that it gets the correct year from the WordPress loop.

I hope this may be of help to anyone trying to set up slightly different archive links.


Google