• I want to show the latest 2 posts on my home page but ONLY if they were published in the last month (at the moment I have the last 3, but as I have been otherwise occupied and haven’t published, they are very old and it looks ridiculous).

    It’s outside the loop so it would have to use get_post(). I can find how to create a conditional filter using dates for query_post() but not for get_post()and not being a programmer I can’t work out how to apply it.

    It seems I need some sort of function because I want first to create an array of the last 2 posts, check their date of publication and if one or both satisfy the condition of being younger than 30 days, do something (put a heading in the div) and, if not, do nothing. Then for the articles that satisfy the date criteria, output the title, excerpt and date.

    I think I can see the mechanics of it – it’s the detail that completely flummoxes me !

Viewing 3 replies - 1 through 3 (of 3 total)
  • After first using get_posts to get the last two posts, run this if statement at the start of your loop.

    if ( $posts->post_date > ' . date( 'Y-m-d', strtotime('-30 days') ) ) { 
    
       // output here 
    
    }

    I haven’t tried that, but I think it should work. It does of course assume that you’re storing the results of the get_posts query in $posts.

    Actually, sorry, first you’ll have to do a foreach statement:

    foreach ($posts as $post) {
       if ( $post->post_date > ' . date( 'Y-m-d', strtotime('-30 days') ) ) {
         // output here
       }
    }
    Thread Starter nick_nielsen

    (@nick_nielsen)

    Thanks for your help
    I’ve tried it and all I get is a parse error ! With my limited understanding, I can’t see what I’m doing wrong.

    here’s my code

    <?php
     $postslist = get_posts('numberposts=2');
     foreach ($postslist as $post) {
        setup_postdata($post);
        if($post->date > '" . date('Y-m-d', strtotime('-30 days')) . "'){ //if($post->date>'.date('Y-m-d',strtotime('-30 days'))'):
     ?>
     <div class="tease">
    
     <h3><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?> </a></h3>
     <?php the_excerpt() ?>
      </div>
      <?php };//endif; ?>
     <?php };//endforeach; ?>

    I’d still like to find a way to check if $posts contains any articles after filtering for date…

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Publish only recent posts using get_post()’ is closed to new replies.