wp-content ยป themes ยป functions.php ยป Show how many minutes and hours ago WordPress post was published โŒ›๐Ÿ•‘ย 

Show how many minutes and hours ago WordPress post was published โŒ›๐Ÿ•‘ย 

While developing a custom site I was in a need to represent how many minutes/hours/days the post was published ago instead of the published date.

The logic of the code is simple:

TIMEDISPLAY
less than 1 hourXX minutes ago
1 – 24 hoursXX hours ago
24 hours – 7 daysXX days ago
more than 7 daysdefault time

Code snippet:

function Bing_filter_time() {
    global $post ;
    $to = time();
    $from = get_the_time('U') ;
    $diff = (int) abs($to - $from);
    if ($diff <= 3600) {
        $mins = round($diff / 60);
        if ($mins <= 1) {
            $mins = 1;
        }
        $time = sprintf ( _n ( '%s minutes' , '%s minutes' , $mins ) , $mins ) . __ ( 'Front' , 'Bing' ) ;
    } else if (($diff <= 86400) && ($diff > 3600)) {
        $hours = round($diff / 3600);
        if ($hours <= 1) {
            $hours = 1;
        }
        $time = sprintf ( _n ( '%s hours' , '%s hours' , $hours ) , $hours ) . __ ( 'Front' , 'Bing' ) ;
    } elseif ($diff >= 86400) {
        $days = round($diff / 86400);
        if ($days <= 1) {
            $days = 1;
            $time = sprintf ( _n ( '%s days' , '%s days' , $days ) , $days ) . __ ( 'Front' , 'Bing' ) ;
        } elseif ($days > 29) {
            $time = get_the_time(get_option('date_format'));
        } else {
            $time = sprintf ( _n ( '%s days' , '%s days' , $days ) , $days ) . __ ( 'Front' , 'Bing' ) ;
        }
    }
    return $time;
}
add_filter('the_time','Bing_filter_time');
See also  Show the number of total 👁️ views for all posts inside a WordPress category

Was this post helpful?

2 thoughts on “Show how many minutes and hours ago WordPress post was published โŒ›๐Ÿ•‘ย ”

Leave a Comment

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.

Recommended