Only show posts if they’re less than 3 days old

Problem: User would like to add a “breaking news” just under the header on site’s custom front page. He wants to show only those posts that are less than 3 days old from a specific category.
His opinion is to put the entire mini-loop inside a php if statement then compare the post date to a number and only print the breaking news ticker if it is less than that number. If there aren’t any breaking news posts in three days, the ticker doesn’t show up any thing.
Users mini-loop working beautifully, posting the 6 most recent news posts on a static home page, using this code:

$my_query = new WP_Query('category_name=news&showposts=6');
while ($my_query->have_posts()) : $my_query->the_post();
$do_not_duplicate = $post->ID;
echo ''.the_title().'';
endwhile;

Solution:
// 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 "

Breaking News:";
the_title();
echo "

";
}
endwhile;

I hope this helps you out.

Conclusion: Above code will help you to solve your query. Without requirements or design, programming is the art of adding bugs to an empty text file. And finding bugs and solve them is also an art.

Leave a Reply

Your email address will not be published. Required fields are marked *