Support » Fixing WordPress » Querying posts over the past X days

  • Resolved jimmiejo


    I’m currently using a query method that I found in these forums a while back, which allows you to query posts for the current month and year, like so:

    <?php $current_month = date('m'); ?>
    <?php $current_year = date('Y'); ?>
    <?php query_posts("showposts=5&year=$current_year&monthnum=$current_month") ?>   
    <?php while (have_posts()) : the_post(); ?>

    It does the job as the month progresses, but the beginning of each month means the lists start with a blank slate, which can look extremely awkward.

    My question is, are they any ways to run a query for the past say 7 or 14 days? Each day the list would bump up and include the current one, and scrap the last day in the list (8th or 15th day).

    Thanks in advance guys.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Might need to add something like this in your loop instead of using a parameter in your query_posts:

    $mylimit=46 * 86400; //days * seconds per day
    $post_age = date('U') - get_post_time('U');
    if ($post_age < $mylimit) {
    echo 'this post is within my date limit ';

    Thanks Michael. Sorry for the late reply, I wasn’t able to test that code until this evening.

    It does exactly what I was after. Much appreciated.

    Great stuff. Where in the loop do I put this code?

    trex33, you would place that within your loop like so:

    <?php query_posts("showposts=5") ?>
    <?php while (have_posts()) : the_post(); ?>
    <?php $mylimit=15 * 86400; //days * seconds per day
    $post_age = date('U') - get_post_time('U');
    if ($post_age < $mylimit) { ?>
    // your post elements here
    <a href="<?php the_permalink() ?>" rel="bookmark">
    <?php } ?>
    <?php endwhile; ?>

    Jimmiejo – many thanks! Works like a charm.

    Only issue is some kind of conflict with PageNavi plugin. Still shows all of the pages even if there is only one. No problem though.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Querying posts over the past X days’ is closed to new replies.