Making monthly archive dropdown lists in WordPress
30 July 2005I was asked by Armand how to do the month-by-month blog archive drop-down in the right hand column of the blog, which, if you have archives going back some time, saves having an enormous list of months (which, IMHO, looks ugly). WordPress’s get_archives() function does provide drop-down capability, but only by using JavaScript to handle the form submission, which is just dumb, and breaks badly if you don’t have JavaScript enabled.
So, I wrote a hack that does the drop-down, but handles it using standard HTTP form submission (which is nice). There is a bit of JavaScript, an event handler to submit the form straight away when a selection is made, but this is a convenience thing, and it still works the old-fashioned way if you have JavaScript disabled.
Here goes… first of all it’s just a hack, not a plugin, so you’ll need to have a my-hacks.php file set up and running – see here for more details.
Once you have my-hacks.php open, add the following inside the PHP code:
function make_month_dropdown() {
global $wpdb, $tableposts, $month;
$now = current_time('mysql');
// Get the entries grouped by month and year
$archiveEntries =
$wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`,
MONTH(post_date) AS `month`
FROM $tableposts WHERE post_date < '$now' AND post_status = 'publish'
GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC");
// Start form
echo '<form action="'.get_settings('home').'/" method="get">';
echo '<div><select name="m" class="small" onchange="this.form.submit();">';
// Produce each line of the dropdown
foreach($archiveEntries as $archiveEntry) {
// Add leading zero
$thisMonth = zeroise($archiveEntry->month,2);
// value to be passed into query string
$thisM = $archiveEntry->year.$thisMonth;
echo "<option value=\"$thisM\"";
// Preselect currently-viewed month
if ($thisM == $_GET['m']) echo ' selected="selected" ';
echo '>';
echo $month[$thisMonth].' '.$archiveEntry->year;
echo '</option>';
}
echo '</select> ';
echo '<input type="submit" value="»" />';
echo '</div></form>';
}
Save that (and upload). Then in your template file (sidebar.php), replace the line beneath the archive header, that says <?php get_archives(); ?> (or something similar) with:
<?php make_month_dropdown(); ?>
And you should be done. Hopefully. Feedback in the comments below.












