Previous and Next Month Links in Archives

It has just taken me around an hour to try and insert some previous and next month navigation links to the blog monthly archives. It seems that WordPress doesn’t have any real native support for this time of navigation which is odd.

The code below is my very hacky version of how to do it. I placed this in my theme’s archive.php file


<?php //twentyeleven_content_nav( 'nav-above' ); ?>
<nav id="nav-above" style="display:inline">
<?php
$archive_year = get_the_time('Y');
$archive_month = get_the_time('m');
$archive_month = $archive_month - 1;
if ($archive_month == 0) {
$archive_month = 12;
$archive_year--;
}
$archive_month_next = $archive_month + 2;
$archive_year_next = $archive_year;
if ($archive_month_next > 12) {
$archive_month_next %= 12;
$archive_year_next++;
}
echo '<a href="' . get_month_link( $archive_year, $archive_month) . '">Previous Month</a>';
if ($archive_year_next.sprintf('%02d', $archive_month_next) < = date('Y', strtotime("now")).date('m', strtotime("now"))) { echo '<a href="' . get_month_link( $archive_year_next, $archive_month_next) . '" style="float:right">Next Month</a>'; } ?> </nav>