Adjust Time Display Based on Post Freshness in WordPress

While looking at the Ali Baixiu website today, I noticed a thoughtful detail. As shown below, the display format of a post’s publish time changes depending on how fresh the content is. For example, if a post was published today, the exact publish time down to the minute is displayed. If it was published yesterday, it simply shows “Yesterday”. For older posts, it just displays the date.

time

I think this approach gives a very good user experience, so I spent a little time looking into how it works. The implementation is actually quite simple. First, get the post publish time. Then get the current time. Compare the two values and decide how the publish time should be displayed based on the result. The code is as follows.

<?php
    $post_time = get_the_time('U');
    $now = current_time('timestamp');
    $diff = (int) abs( $post_time - $now );
    $days = round( $diff / DAY_IN_SECONDS );
?>
<?php if($days < 1){?>
    <time class="new"><?php the_time("A g:i"); ?></time>
<?php }elseif($days == 2){ ?>
    <time class="prev">Yesterday</time>
<?php }else{?>
    <time class="new"><?php the_time("m-d"); ?></time>
<?php }?>

This is the complete logic for switching the display format based on how recent the post is.

You can just copy the code above directly into the place where you want it to appear. Of course, we can also wrap the same behavior into a function so we do not need to repeat that much code every time, and the template will look cleaner as well.

A function for adjusting time display based on post freshness

Someone asked how to turn the logic above into a function. To make it easier for everyone, here is the function version directly.

function wizhi_human_time(){

    $post_time = get_the_time('U');
    $now = current_time('timestamp');
    $diff = (int) abs( $post_time - $now );
    $days = round( $diff / DAY_IN_SECONDS );

    if($days < 1){
        echo '<time class="new">' . the_time("A g:i") . '</time>';
    }elseif($days == 2){
        echo '<time class="prev">Yesterday</time>';
    }else{
        echo '<time class="new">' . the_time("m-d") . '</time>';
    }

}

Paste the function above into your theme’s functions.php file, then call it like this wherever you need it:

<?php wizhi_human_time(); ?>

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *