You can do all of this outside the template, via the pre_get_posts
action and a filter on posts_where
.
The first function checks if it’s the main query and the home page, if so it applies a filter to the query’s posts_where
clause.
The posts_where
function limits post selection to today’s date minus 7 days, then immediately removes the filter so it isn’t applied to any other queries on the page.
You can put this in your theme’s functions.php
file, then edit your template to remove all of the query trickery, and just run the normal loop.
function wpa85491_home_filter( $query ) {
if ( $query->is_home() && $query->is_main_query() )
add_filter( 'posts_where', 'wpa85491_filter_where' );
}
add_action( 'pre_get_posts', 'wpa85491_home_filter' );
function wpa85491_filter_where( $where="" ) {
$where .= " AND post_date > '" . date( 'Y-m-d H:i:s', strtotime( '-7 days' ) ) . "'";
remove_filter( 'posts_where', __FUNCTION__ );
return $where;
}