Get posts published within the past month using WP_Query

by Dan
Last updated: September 26th, 2020

I recently had to create a “What’s new?” Dashboard area for members of The Luminous that returned all posts (or in The Luminous case, images, Canva templates and education resources) that were published inside of the past 30 days, meaning that members only ever saw the very latest content.

Since I was using multiple loops on one page I turned to WP_Query to create custom loops for this functionality, but you could just as easily modify the main query using the pre_get_posts() function.

I used the query to fetch everything published in the past 30 days, but you can modify the query to return posts from as many days as you need.

$args = array( 'post_type' => 'posts', 'posts_per_page' => 20, 'date_query' => array( array( 'after' => '-30 days', 'column' => 'post_date', ), ), ); $loop = new WP_Query( $args ); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); // add your loop content here endwhile; wp_reset_postdata(); // Reset query incase we want to use another query on the same page endif; ?>
Code language: PHP (php)

we think you'll probably like these too