Support » Plugins » Hacks » Use publish date instead of current date to retrieve a range of posts?

  • I’d like to create a separate category of posts where I can just publish “A year ago on…” type posts that will dynamically retrieve a list of posts within a date range relative to the date the post is published.

    Essentially I would publish a post with just a title and when placed in that category, the loop builds the list of posts from the same week as the publish date, but from one year or two years ago, etc.

    I have some general code in the single.php that filters out posts in the right category, but it seems I can only pull in posts relative to today’s date and not the publish date of that a particular post. And ideas how to make the date range relative to the publish date and not the current day?

    I can build the loop – I just don’t know how to manipulate the dates. Any help would be appreciated.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Forgive me if I’m misunderstanding what you’re trying to do. 🙂

    You can build time information into the query_posts command. To get all posts from the first week of last year, you’d use query_posts(‘year=2010&w=1’)

    If you’re trying to get the posts publishing during this week last year, just do a bit of date math before throwing it into query_posts.

    $week = date('W');
    $year = date('Y') - 1;
    query_posts('year= ' . $year . '&w= ' . $week . ');

    See also: Query Posts Time Functions

    Thanks – this does what I want in terms of retrieving the range, but it retrieves it based on the current date. I want it to retrieve the range based on the publish date.

    So I can publish a post for say February 7th and it will pull in all posts from Feb 1-7, 2010 and 2009, etc. Right now, every post I either publish or schedule in this category shows the same posts based on today’s date. Once the post is published, I don’t want the contents to change whenever the date rolls over. Does that make sense?



    Forum Moderator

    untested, but try:

    $week = get_the_time('W');
    $year = get_the_time('Y') - 1;
    query_posts('year= ' . $year . '&w= ' . $week . ');

    and because you are using this in the loop, try to use get_posts() instead of query_posts()

    For what it’s worth, I got this working… not sure what I screwed up the first time, but here is the code that works:

    [Code moderated as per the Forum Rules. Please use the pastebin]

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Use publish date instead of current date to retrieve a range of posts?’ is closed to new replies.