Reputation: 1227
Although following code is for WordPress, but my question is more about general PHP loop.
I want to get posts of last 7 days. I want to get only last 7 days which have posts. If some day does not have any post, it should skip to next day.
I am using following loop to get posts from last 7 days, but the problem is that if a day does not have post, it will loop through last 7 days only, no matter if there's any post or not.
So, I have tried to extend $i value only if there is post, but if I place it inside the if condition, it will run infinite times. Thanks for any help about this.
$day = date('j');
while( $i <= 7){
query_posts('day='$day);
if (have_posts()){
//list posts.
}
$i++;
$day--;
}
Upvotes: 0
Views: 131
Reputation: 16184
You could set a maximum for the loop and query by date rather than day:
$date = date('Y-m-d');
$maxAttempts=100;
$postCount=0;
while( $i <= $maxAttempts && $postCount <= 7 ){
query_posts('date='$date);
if (have_posts()){
//list posts.
$postCount++;
}
$i++;
$date = date('Y-m-d', strtotime($date .' -1 day'));
}
Upvotes: 1
Reputation: 490233
You could change your loop to only increment $i
if a post was found, which would mean the loop would run until it found 7 posts. Be sure to handle the case where it can never find 7 posts.
Upvotes: 0
Reputation: 13
Try this...
$day = date('j');
$post_days_count = 0;
while( $post_days_count < 7){
query_posts('day='$day);
if (have_posts()){
$post_days_count++;
//list posts.
}
$day--;
}
Upvotes: 0