0

My goal is to use human_time_diff only when the post was added on the current day. When it wasn't, I would like to revert to the traditional timestamp (the second code). I'm unsure how this would be achieved and need some help. I have provided the two codes I would be combining below.

The code for grabbing the difference between the posting time and current time (i.e. 25 minutes ago):

<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?> 

The code for stating the post was added on X date at X time:

<?php the_time('F j, Y'); ?> at <?php the_time('g:i a'); ?>
2

You can get the post's creation date/time and compare it to the current date/time.

global $post;
$now = time(); // Current time in seconds since Epoch
$post_created = strtotime( $post->post_date );  // post's creation date in seconds since Epoch, so we're comparing apples to apples
$one_day_in_seconds = 24*60*60;
if ( ( $now - $post_created ) < $one_day_in_seconds ) {
    echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago';
} else {
    the_time( 'F j, Y \a\t g:i a' );
}

References

PHP.net:
time()
strtotime()

Codex:
Post Object (for the post_date)

1

You need to express your condition in code. You are interested in comparing to current day, which can be expressed as PHP format Y z for example.

So your condition would be something like (not tested):

if ( the_time( 'Y z' ) === date_i18n( 'Y z' ) )

    // today

else

   // otherwise

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.