How to get date for each post?

I’m using the following to get the date of each post:

while (have_posts()) : the_post();
//some html
<li class="icon-date"><?php the_date('Y-m-d');?></li>
<li class="icon-time"><?php the_date('H:i:s');?></li>

However, I am only getting the date for first post why is that?

Related posts

Leave a Reply

2 comments

  1. I ran into the same problem several times, following changes worked for me in the past:

    while (have_posts()) : the_post();
    //some html
    <li class="icon-date"><?php echo get_the_date( 'Y-m-d' ); ?></li>
    <li class="icon-time"><?php the_time( 'H:i:s' ); ?></li>
    

    Instead of the_date(), use get_the_date().
    The only thing to be aware of, is that values returned by get_the_date() have to be echoed.

    Looking at the Codex page there is a special note about the_date().

    When there are multiple posts on a page published under the SAME DAY, the_date() only displays the date for the first post (that is, the first instance of the_date()). To repeat the date for posts published under the same day, you should use the Template Tag the_time() or get_the_date() (since 3.0) with a date-specific format string.

    Also, If you want to control the format in wich get_the_date() is returned in Admin, you can use get_option('date_format'). This way if you change the date format in the Admin, these changes will me made in your code too.

    while (have_posts()) : the_post();
    //some html
    <li class="icon-date"><?php echo get_the_date( get_option('date_format') ); ?></li>
    <li class="icon-time"><?php the_time( 'H:i:s' ); ?></li>
    
  2. When there are multiple posts on a page published under the SAME DAY, the_date() only displays the date for the first post (that is, the first instance of the_date()). To repeat the date for posts published under the same day, you should use the Template Tag the_time() or get_the_date() (since 3.0) with a date-specific format string.
    Use to add the date set in the admin interface.

    For more information visit this page.

    So according to the wordpress codex reference the correct code will be as following :

    while (have_posts()) : the_post();
    //some html
    <li class="icon-date"><?php echo get_the_date('Y-m-d');?></li>
    <li class="icon-time"><?php the_time('H:i:s');?></li>