Making next_posts_link(); return posts by month

You have to modify the query that selects the posts to select by month. This bit of code placed in the template will get the page number and subtract that from the current month.

<?php

$page = get_query_var('paged') ? get_query_var('paged') : 1;
$subtractor = $page-1;
$date = date("Y-m-d H:i:s");
$current_month = date('n', strtotime($date.'-'.$subtractor.'months'));
$current_year = date('Y', strtotime($date.'-'.$subtractor.'months'));
query_posts("monthnum=$current_month&year=$current_year&order=DESC");

if (have_posts()) :
while (have_posts()) : the_post(); // rest of the loop below

Ultimately this is probably best hooked into pre_get_posts to keep it out of the template.

You’d have to make your own pagination links as well, something like:

<?php
if($page>1)
    echo '<a href="https://wordpress.stackexchange.com/page/".($page-1)."https://wordpress.stackexchange.com/">next</a>';

echo '<a href="https://wordpress.stackexchange.com/page/".($page+1)."https://wordpress.stackexchange.com/">prev</a>';

of course, you’d have to figure out how far back the posts go to know when to stop providing a previous month link, hmm…

Leave a Comment