2

The following loop works great for me in getting posts with a given date with the use of the_time(...):

<?php
    $myPost = new WP_Query( array(
    'posts_per_page' => '50',
    'orderby' => 'modified',
    'order' => 'DESC'
    ));
    while ($myPost->have_posts()): $myPost->the_post();
?>

<div class="timeline-group">
<p class="modified-time"><?php the_time('F j, Y') ?></p>
<h5><a href="<?php the_permalink();?>"><?php the_title();?></a></h5>
</div>

<?php
    endwhile;
    //Reset Post Data
    wp_reset_postdata();
?>

But the first 10 posts always show the same date (i.e. July 21, 2017). I want to display that date only once for these 10 posts. And if I create a new post tomorrow, then it should then show a new date under these 10 posts, and then the post associating to that new date. How can I transform my loop to think that way without hard-coding dates?

Thanks

3

Just use the_date(), it has this as a built-in feature.

See the dev docs for more info.

  • 2
    You're welcome. To some devs it looks like a bug at first, but for your case it's a nice feature ;-) – birgire Jul 21 '17 at 22:39
  • @birgire Like when I tried to show the date twice for two days, then finally realized that the_date() intentionally only shows it once. – Jack Johansson Jul 22 '17 at 2:10
  • happened to me too ;-) @JackJohansson – birgire Jul 22 '17 at 9:41
1

You can save the last date on a variable and on each iteration you compare the current date with the last date, and just write the date if they're different:

<?php
    $myPost = new WP_Query( array(
    'posts_per_page' => '50',
    'orderby' => 'modified',
    'order' => 'DESC'
    ));
    $lastDate = '';
    while ($myPost->have_posts()): $myPost->the_post();
    $currentDate = get_the_time('F j, Y');
?>

<?php if($currentDate != $lastDate): ?>
    <h2><?php the_time('F j, Y') ?></h2>
    <?php $lastDate = $currentDate; ?>
<?php endif; ?>

<div class="timeline-group">
<h5><a href="<?php the_permalink();?>"><?php the_title();?></a></h5>
</div>

<?php
    endwhile;
    //Reset Post Data
    wp_reset_postdata();
?>

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.