Blog Post On Home Page Displaying Page Published Date Not Post Published Date

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;
    ?>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x