I’m trying to figure out how to do this. I have many posts. I want it so that when someone pulls up the site, the front page shows all the posts that were done on the same month and day — but disregards the year. So, if I were to pull up the website on Jan. 30, I would see all posts done on Jan. 30th of ANY year… a historical listing. I was also thinking of doing it by category, if the category was named Jan-30, is there a way I can get the system to take today’s date and compare it to the categories, and show the one that matches (no year, of course)?
Can anyone help?
3 Answers
You can achieve this with the date_query
parameters added in version 3.7.
To modify the main query on your posts page before it is run and apply the date_query
parameters, we use the pre_get_posts
action:
function historical_posts_list( $query ){
if( $query->is_home() && $query->is_main_query() ){
$date_query = array(
array(
'month' => date( 'n', current_time( 'timestamp' ) ),
'day' => date( 'j', current_time( 'timestamp' ) )
)
);
$query->set( 'date_query', $date_query );
}
}
add_action( 'pre_get_posts', 'historical_posts_list' );
If the page you want this on isn’t your posts page, you can add a custom query in your template with the same parameters, and run a separate loop:
$posts_from_today = new WP_Query( array(
'date_query' => array(
array(
'month' => date( 'n', current_time( 'timestamp' ) ),
'day' => date( 'j', current_time( 'timestamp' ) )
),
),
'posts_per_page' => -1,
) );
if( $posts_from_today->have_posts() ){
while( $posts_from_today->have_posts() ){
$posts_from_today->the_post();
the_title();
}
}