Support » Developing with WordPress » Only show posts if they’re less than 3 days old

  • Resolved stormrider

    (@stormrider)


    I would like to add a “breaking news” ticker just under the header on my site’s custom front page. I want it to show only posts less than 3 days old from a specific category.

    My thought is to put the entire mini-loop inside a php if clause, compare the post date to a number, and only print the breaking news ticker if it’s less than that number. The idea being if I post something in the “breaking news” category, for the next few days it shows up in a ticker box on the front page. If there aren’t any breaking news posts younger than three days, the ticker doesn’t show up.

    I have the mini-loop working beautifully, posting the 6 most recent news posts on a static home page, using this code:

    <?php
     $my_query = new WP_Query('category_name=news&showposts=6');
     while ($my_query->have_posts()) : $my_query->the_post();
     $do_not_duplicate = $post->ID;
    ?>
    <a>">
     <?php the_title(); ?>
    </a>
    <?php endwhile; ?>

    Any thoughts or ideas, or has anyone done something like this before?

Viewing 1 replies (of 1 total)
  • Thread Starter stormrider

    (@stormrider)

    Half of the problem was that I didnt’ know what to search for. I finally stumbled upon a older post here that helped a bit, and I seem to have hacked this together to make it work how I want.

    It made it a bit ugly, but by changing the number that the posts are measured against I can make the block disappear, which means it’s working right.

    <?php
    // Start of the mini-loop, specifies which category to look in and how many posts to pull//
     $my_query = new WP_Query('category_name=breaking-news&showposts=1');
     while ($my_query->have_posts()) : $my_query->the_post();
     $do_not_duplicate = $post->ID;
    // Adjust 604800 to the number of days in seconds that you want to check against. Posts will only appear if they are newer than that time.//
     if ( (current_time(timestamp) - get_the_time('U') - (get_settings('gmt_offset') * 3600) ) < 604800 )
     {
      echo "<tr><td class=breakingnews colspan=3>Breaking News:<a href=";
      the_permalink();
      echo ">";
      the_title();
      echo "</a> </td></tr>";
     }
    endwhile; ?>

    I hope this helps others out, I’m actually pretty surprised I made this work. If anyone has improvements or suggestions, or if there is a better way to do this, I would be happy to hear them.

Viewing 1 replies (of 1 total)
  • The topic ‘Only show posts if they’re less than 3 days old’ is closed to new replies.