0

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--;
}
3
  • You need to identify the case where you have checked all entries. In other words when your query fails or you go past the first(last) post. Commented Sep 27, 2013 at 19:36
  • What do you want to happen when the $day becomes negative? Commented Sep 27, 2013 at 19:52
  • @Moob this is more complicated than I thought. I want to get last 7 days which have the posts, but now I realized that day (int) is not good idea as it wont work in negative days. I'm just unable to figure out this. Commented Sep 27, 2013 at 19:55

3 Answers 3

1

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'));
}
Sign up to request clarification or add additional context in comments.

Comments

0

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--;
}

1 Comment

Thanks, but I have already tried this, this won't work because the day of the month will go into negative, and if i place $day inside the if condition, it will run infinite.
0

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.

1 Comment

Thanks for the answer, and yes, thats what I'm trying to do. If I place the $i inside the if condition, then the $day would go in negative and the loop wont return correct results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.