WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Querying posts over the past X days (6 posts)

  1. jimmiejo
    Member
    Posted 5 years ago #

    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.

  2. MichaelH
    Member
    Posted 5 years ago #

    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 ';
    }
  3. jimmiejo
    Member
    Posted 5 years ago #

    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.

  4. trex33
    Member
    Posted 5 years ago #

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

  5. jimmiejo
    Member
    Posted 5 years ago #

    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">
    
    etc...
    
    <?php } ?>
    <?php endwhile; ?>
  6. trex33
    Member
    Posted 5 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic