admin管理员组

文章数量:1323348

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

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;
    ?>
Share Improve this question asked Sep 8, 2020 at 9:55 SurreyCreativeSurreyCreative 134 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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

本文标签: Blog Post On Home Page Displaying Page Published Date Not Post Published Date