How would I get custom posts by a WordPress query that excludes the current month? I have a query created that shows the posts published in the current month…
<?php
$currentYear = date('Y');
$currentMonth = date('n');
$args_current_month = array(
'post_type' => 'post',
'post_status' => array('publish', 'future'),
'posts_per_page' => -1,
'date_query' => array(
array(
'year' => $currentYear,
'month' => $currentMonth
)
)
);
$current_month_query = new WP_Query($args_current_month);
?>
But how would I do a query for the opposite and exclude the posts published within the current month?
I tried the below query and was expecting it to exclude the posts in the current month but it doesn’t…
<?php $currentMonthPosts = array(
'post_status' => array('publish', 'future'),
'date_query' => array(
array(
'year' => $currentYear,
'month' => $currentMonth
)
)
);
$args_future = array(
'post_type' => 'post',
'post_status' => array('future'),
'posts_per_page' => -1,
'post__not_in' => $currentMonthPosts,
);
$future_query = new WP_Query($args_future);`
?>
2
Answers
Using
before
you can achieve this, source: WordPress Date QueryCode:
P.S: @Luuk helped with improvements to the answer.
I think your answer can be found in the documentation:
https://developer.wordpress.org/reference/classes/wp_query/#date-parameters
You can set a date range and get all posts within the specified dates.
Example: get all posts in this year except this month.