Family Encyclopedia >> Electronics

How to Display Last Week's Posts in WordPress: Simple WP_Query Guide

As seasoned WordPress developers who've guided thousands of users through customizations, we know beginners often dive into theme tweaks early. Our comprehensive WordPress cheat sheets make it easier. A recent reader wanted to showcase last week's posts on their homepage. Here's our proven method to display them using WP_Query.

Let's start with displaying current week's posts. Add this reliable code to your theme's functions.php or a site-specific plugin:

function wpb_this_week() {
    $week = date('W');
    $year = date('Y');
    $the_query = new WP_Query('year=' . $year . '&w=' . $week);
    if ($the_query->have_posts()) :
        while ($the_query->have_posts()) : $the_query->the_post();
            ?>
            <?php // Add your post display code here, e.g., the_title(), the_excerpt() ?>
            <?php
        endwhile;
    endif;
    wp_reset_postdata();
}</pre>

This code grabs the current week and year, then queries posts accordingly. Insert <?php wpb_this_week(); ?> in your theme template where needed.

Simple enough? For last week's posts, subtract 1 from the week—but handle year transitions carefully (e.g., week 1 can't go to week 0). Here's the battle-tested fix:

function wpb_last_week_posts() {
    $thisweek = date('W');
    if ($thisweek != 1) :
        $lastweek = $thisweek - 1;
    else :
        $lastweek = 52;
    endif;

    if ($lastweek != 52) :
        $year = date('Y');
    else :
        $year = date('Y') - 1;
    endif;

    $the_query = new WP_Query('year=' . $year . '&w=' . $lastweek);
    if ($the_query->have_posts()) :
        while ($the_query->have_posts()) : $the_query->the_post();
            ?>
            <?php // Customize post output here ?>
            <?php
        endwhile;
    endif;
    wp_reset_postdata();
}</pre>

Key checks: If current week is 1, set last week to 52 and prior year. Place <?php wpb_last_week_posts(); ?> in your template.

For flexibility, add a shortcode by appending this after the function:

add_shortcode('lastweek', 'wpb_last_week_posts');</pre>

Use it anywhere: [lastweek] in posts, pages, or widgets.

Pro tip: WordPress offers built-in functions for recent posts or archives—use them when simpler. No need for custom queries everywhere.

This approach has powered sites for years. Tweak as needed, and drop questions in comments or follow us on Twitter for more tips.