0

I am displaying the latest post from my blog on a custom home page template but the date posted for the post is pulling through the date the homepage was published not the date the post was published. How can I fix this. Here is my code.

<?php 
        $args = array(
        'posts_per_page' => 1,
        'order' => 'DESC'
        );

        $rp = new WP_Query( $args );
        $post_date = get_the_time( 'd-m-y', $post->ID );

        if($rp->have_posts()) :
        while($rp->have_posts()) : $rp->the_post();
        echo '<p class="authDate">Surrey Creative | ';
        echo $post_date;
        echo '</p>';
        echo '<h3>';
        the_title();
        echo '</h3>';
        echo '<div class="snippet">';
        the_excerpt();
        echo '</div>';
        echo '<a href="'; 
        echo esc_url( get_the_permalink( $post_id ) );
        echo '" class="read-more button link">';
        echo 'Read More <i class="fa fa-angle-right"></i></a>';                

        endwhile;
        wp_reset_postdata(); 
        endif;
    ?>
2

That's expected, this code gets the date of the current post:

$post_date = get_the_time( 'd-m-y', $post->ID );

But you're not inside the post loop yet, so the current post is the page you're on. the_post is what sets the current post, so you need to call this inside the loop, not outside.

There are some other issues:

  • Use an editor that auto-indents code, especially if you're sharing it, indentation avoids an entire group of bugs
  • echo esc_url( get_the_permalink( $post_id ) ); refers to $post_id which is never defined, it's just pulled out of thin air
  • There is no else case, if no posts are found it'll just be blank
3
  • Thanks for the insight Tom. However the problem remains because I am just displaying the latest post on the home page, I am not doing so within the loop. is there a way of grabbing the post date to display here whilst remaining outside of the loop? – SurreyCreative Oct 1 '20 at 8:34
  • There's no reason to grab it outside the loop in the code you posted, in fact it is the cause of your problem. Notice I'm not talking about the main post loop, but your custom post loop with $rp->. $rp->the_post sets the current post, but you fetched the date before that, and that's the fundamental mistake. get_the_time uses the current post, and $post is the current post. Until you call $rp->the_post() the current post is the homepage. After you call $rp->the_post() the current post is changed. Keep in mind it's harder to see this because all the indentation is the same – Tom J Nowell Oct 1 '20 at 11:45
  • Hero thanks tom, makes sense now and that's fixed it. – SurreyCreative Oct 8 '20 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.