WordPress gives you the option to change a post’s publication date and it provides you with get_the_date() to easily fetch it on the frontend. What happens, though if, for whatever reason, you want to access the actual date that the post had been created, instead of the one that you manually set?

Apparently, WordPress keeps the _wp_old_date meta key which stores the old date every time it changes. You can easily retrieve this using get_post_meta(). So, echoing get_post_meta( get_the_ID(), '_wp_old_date' ); would give you an array with all the old dates:

array (size=3)
  0 => string '2020-03-14'
  1 => string '2020-03-21' 
  2 => string '2020-03-11'

According to the documentation, get_post_meta() accepts a third, optional parameter which if set to true will return only the first value. So, we can easily get the post creation date simply by usingĀ  get_post_meta( get_the_ID(), '_wp_old_date', true );.

Here is the catch, though: If you never changed the post’s date, _wp_old_date will be empty. To deal with it, we need to check if _wp_old_date is empty and if it is, we fall back to our familiar get_the_date(). If it does have a value we can return it, keeping in mind two things:

  1. We would probably want to maintain the display format that is set by the Admin on WordPress options. We can fetch that with a simple get_option( 'date_format' ).
  2. We should also use date_i18n, to make sure that we retrieve the date in a localized format.

So, in the end, a more future-proof function would probably look something like that:

function get_creation_date( $entry_id = '' ) {
  $post_id  = $entry_id ? $entry_id : get_the_ID();
  $old_date = get_post_meta( $post_id, '_wp_old_date', true );

  return $old_date ? // If the old date exists
    date_i18n( get_option( 'date_format' ), // Retrieve the date in localized format
      strtotime( $old_date ) ) : // and use the display format set on WordPress options
    get_the_date(); // else, use get_the_date()
}

If you believe that there is a better way to deal with the issue or if you have any suggestions on how it could be further improved, let me know in the comments!

Leave a Reply

Your email address will not be published.

We use cookies. By browsing our site you agree to our use of cookies. Read moreAccept