This approach doesn’t work for January:
$lastMonthNumber = date( 'n', current_time( 'timestamp' ) ) - 1;
as it would give 1 - 1 = 0
.
Here’s another suggestion, using the string to time support of the date query:
$query->set( 'date_query', [
[
'after' => 'midnight first day of last month',
'inclusive' => true,
],
[
'before' => 'midnight first day of this month',
'inclusive' => false,
]
] );
For example this should generate:
wp_posts.post_date >= '2018-05-01 00:00:00' AND wp_posts.post_date < '2018-06-01 00:00:00'
if the current day is 27th of June 2018.
Note that pre_get_posts
is an action, not a filter.