[WordPress] How to retrieve posts published in the last 7 days (or N days)

Saul Goodman October 30, 2019 Loading...

This guide demonstrates how to get posts (pages, custom post type) that published in the last 7 days (one week) or 30 days (one month) or N days.

The code:

   <?php
    $my_args = [
        'post_type' => ['post'],
        // if you want more, use ['post', 'page', 'your-custom-post-type']
        'posts_per_page' => 10,
        // 10 or any number you like
        'date_query' => [
            'after' => date('Y-m-d', strtotime('-7 days'))
             // 1, 2, 3, 7 or 30 or 90 or 9999
        ]
    ];

    $my_query = new WP_Query($my_args);
    
    // the loop
    while($my_query->have_posts()){
        $my_query->the_post();
        // display the title, excerpt, thumbnail, date...
        // just make them suit your HTML & CSS design
        ?>
            <h2><?php the_title(); ?></h2>
            <div><?php the_excerpt(); ?></div>
        <?php
    }

    wp_reset_postdata();
?>

  • Tag
  • avatar
    Welcome to KINDACODE. Have a nice day and code well!