1

On my homepage I am showing only the current month's posts. I'd like to include a link to the previous month's posts at the bottom of the page.

Wordpress has get_month_link (http://codex.wordpress.org/Function_Reference/get_month_link). I can use this function like so to get the month number, minus 1 = previous month:

$archive_year  = get_the_time('Y'); 
$archive_month = get_the_time('m');
$previous_month = $archive_month - 1

<a href="<?php echo get_month_link( $archive_year, $previous_month ); ?>">Last month's posts</a>

This will output a link like "/?m=201308" if the month is September.

In most cases this will work, but when I get to January, the $previous_month var will be "01 - 1", and won't give me "12" for December's posts.

Any ideas how to make this a little more fail-safe for situations like December?

Many thanks

2
$archive_month = date('m', strtotime('1 month ago') );
$archive_year  = date('Y', strtotime('1 month ago') ); 
echo '<a href="' . get_month_link( $archive_year, $archive_month) . '">Last month\'s posts</a>';
  • Thanks! That works really nicely (I escaped the ' in month's). Just a thought on the January back to December issue, It'll also need to skip back one year. Will $archive_year skip back a year as well as the month, when querying January < December posts? Cheers. – Dave Sep 7 '13 at 9:52
  • It works as you can expect. On January 2014 it will return m=201312. See strtotime docs @Dave – gmazzap Sep 7 '13 at 10:13
  • This will create a lot of 404s. You assume there will always be a post in the exact previous month or year. – Aeyoun Aug 31 '17 at 3:05
  • @Aeyoun This code is not sending any HTTP request, just creating a link, so how could it generate 404s? Sure, if the user clicks the link, and there's no posts in that year/month the result will be a 404, so what? That's exactly what is is supposed to do. – gmazzap Aug 31 '17 at 9:38
  • 1
    Check the database and check which months have posts and only link to the next/previous month that has posts. Blindly linking to a page that may or may not have any content is a bad user experience. – Aeyoun Sep 1 '17 at 10:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.