Many of our beginner level readers soon start modifying their WordPress themesthats why we have a WordPress theme cheat sheet to help them get started. This brings some interesting challenges for new users. One such reader, recently asked us how to display last week’s posts in WordPress. They just wanted to add a section on their home page which displayed posts from previous week. In this article, we will show you how to display last week’s posts in WordPress.

Before we show you how to display previous week’s posts, let’s first take a look at how you can display current week’s posts using WP_Query. Copy and paste the following code in your theme’s functions.php file or a site-specific plugin.

01 function wpb_this_week() {
02 $week = date('W');
03 $year = date('Y');
04 $the_query = new WP_Query( 'year=' . $year . '&w=' . $week );
05 if ( $the_query->have_posts() ) :
06 while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
07     <h2><a href="<?php the_permalink(); ?>" title="Permanent link to <?php the_title(); ?> "><?php the_title(); ?></a></h2>
08     <?php the_excerpt(); ?>
09   <?php endwhile; ?>
10   <?php wp_reset_postdata(); ?>
11 <?php else:  ?>
12   <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
13 <?php endif;
14 }

In the sample code above we have placed two checks. The first check sets the last week’s value to 52 (which is the last week in a year) when the current week’s value is 1. The second check sets year’s value to last year when the last week’s value is 52.

To display last week’s posts all you need to do is add <?php wpb_last_week_posts(); ?> to your theme’s template file where you would like to display them. Or if you would like to have a shortcode so that you can add this into a page or a widget, then simply add this line below the code given above.

1 add_shortcode('lastweek', 'wpb_last_week_posts');

You can now use this shortcode in a post, page, or a widget like this:


Please note, that you don’t always need WP_Query to create custom queries. WordPress comes with a handful of functions to help you display recent posts,archives, comments, etc. If there is an easier way to use the existing functions, then you don’t really need to write your own queries.

We hope this article helped you display last week’s posts in WordPress. Experiment with the code and modify it to meet your needs. Let us know if you have any questions by leaving a comment below or join us on Twitter.

Content Source