Post Pic

WordPress loop: Get posts published between two particular dates

WordPress loop is very powerful, as well as the query_posts() function, which allow you to specify some parameters for the loop to retrieve posts. Though, there’s no built-in function or parameter to get posts between two dates. Let’s solve that.

Open your index.php file and find the loop. Just before the loop starts, paste the following code. Of course, don't forget to change the dates on line 3 according to your needs.

<?php
  function filter_where($where = '') {
        $where .= " AND post_date >= '2009-05-01' AND post_date <= '2009-05-15'";
    return $where;
  }
add_filter('posts_where', 'filter_where');
query_posts($query_string);
?>

Credit: WordPress Codex.

31 Responses

May 08 2009 13:40

nice tips. I’ll try. btw, thanks for sharing

May 08 2009 14:33

Thanks a lot. Very useful

May 08 2009 17:56

Another great tip. Your site will achieve randomness which is good for SEO. THanks, again.

May 08 2009 22:58

Interesting recipe. You can do so much with Wordpress!

May 09 2009 00:28

Very usefull, thanks

May 09 2009 15:54

Interesting. Could you use this to display the next post in the future?

I know you can use post_status=future but I needed to use “The Future is Now” plugin so that doesn’t work anymore.

May 12 2009 17:38

I gotta tell you, I found this blog about a month ago, and have been bookmarking literally every entry! Great, simple stuff- Keep it rocking!

May 13 2009 19:28

Hehe, this one is seriously very interesting. You never know for which reason you may come into situation to filter posts by custom dates, and in such a case, this is perfect solution.

Jun 02 2009 11:12

It didn’t work for me. I wanted to mail you but then I realised that I forgot to past a part of the last line. Rewrote it and everything’s working perfectly. Good job.

Jun 11 2009 15:18

Thanks, its work…

Feb 18 2010 18:04

Hi, thanks for this great website and for your great tutorial !
I would like to display the news of the 3 last days on my wordpress home page like this :
jeudi 5 janvier
09h00 – titre news 1
10h00 – titre news 2
11h00 – titre news 3
vendredi 5 janvier
09h00 – titre news 1
10h00 – titre news 2
11h00 – titre news 3

Your tutorial is very interesting but is it possible to replace the date by the last 3 days, and if OK how to do this ?
Thanks in advance, I am looking for this for a long time ;) !

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required