Are You Using the_date() In WordPress? Don’t!

November 5, 2017 by Andreas Wik

Are you using the function the_date() when listing your posts in WordPress? Well, don’t! It’s about time to change that.

Don’t worry though, it’s not as dramatic as the headline suggests. It doesn’t open up some hidden backdoor to your admin area. But there is another reason to why you shouldn’t use it.

I noticed it about a week ago. I was building a WordPress theme and here is the loop I was using:

<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
?>
  <h1><?php the_title(); ?></h1>
  <span class="the-date"><?php the_date(); ?></span>
  <p><?php the_excerpt(); ?></p>
<?php
endwhile;
?>

 

I created a few dummy posts, but only one of them was showing the date it was published. What the heck?

Output:

Buy your own island
Posted on 2 February 2017

Move to Kambodja
Posted on

The hottest venues in Philly right now
Posted on

 

It turns out that in case you have two or more posts published on the same date and they are listed on the same page, the_date() will only print the date for the first one. That’s no good if you get all emotional after a few Margaritas one night and decide to publish a load of poetry.

 

The alternative

So instead of the_date(), we can simply use get_the_date() which will return the exact same thing, unless you provide it with a date format parameter. Oh, and remember to add echo when you use this. Unlike the_date(), it doesn’t do this for you. So here is the new loop:

<?php
if ( have_posts() ) : while ( have_posts() ) : the_post();
?>
  <h1><?php the_title(); ?></h1>
  <span class="the-date"><?php echo get_the_date(); ?></span>
  <p><?php the_excerpt(); ?></p>
<?php
endwhile;
?>

 

Output:

Buy your own island
Posted on 2 February 2017

Move to Kambodja
Posted on 2 February 2017

The hottest venues in Philly right now
Posted on 2 February 2017

 

That’s better.

Well, that’s all there is to it. You can read more about these functions on wordpress.org.

Cheers.

Share this article

Recommended articles