Programming, WordPress

Time ago implementation

WordPress has a function to determine the difference between two timestamps. Time ago can be implemented in the WordPress Post, using get_the_time() and human_time_diff() functions.

$postedTime = get_the_time(‘U’,$post->ID); //Returns Unix timestamp
get_the_time() function retrieves the time at which the post was written.

human_time_diff( int $from, int $to ), determines the difference between two timestamps by providing the posted date of the post and current time.

$timeAgo = human_time_diff($postedTime ,current_time( ‘U’ ));

Example:

<?php
$args = ['post_type'=>'news',
'posts_per_page' => -1,
'post_status' =>'publish'
];
$query = new WP_Query($args);
while ($query->have_posts()):$query->the_post();
$posted = get_the_time('U'); ?>
<ul class="list-unstyled">
    <li ><?php the_title(); ?></li>
    <li class="post-date">
        <?php  echo "Posted " . human_time_diff($posted,current_time( 'U' )). " ago";?></div>
    </li>
</ul>
<?php
endwhile;

Click to learn more about get_the_time() and human_time_diff() functions in codex.

Code to determine the difference between two timestamps in PHP:

function getHumanTimeDiff($time) {
	$now = new \DateTime();
	$interval = $now->diff(new \DateTime($time));
	if ($interval->invert == 0) return 'just now';
	if ($interval->y == 1) return $interval->format('a year ago');
	if ($interval->y > 1) return $interval->format('%y years ago');
	if ($interval->m == 1) return $interval->format('a month ago');
	if ($interval->m > 1) return $interval->format('%m months ago');
	if ($interval->d == 1) return $interval->format('yesterday');
	 if ($interval->d > 1)
        {

            $w = (int)(($interval->d % 365) / 7);
            if($w == 1)
            {
                return $interval->format($w.' week ago');
            }

            if($w > 1) {
                return $interval->format($w.' week ago');
            }

            return $interval->format('%d days ago');
        }
	if ($interval->h == 1) return $interval->format('an hour ago');
	if ($interval->h > 1) return $interval->format('%h hours ago');
	if ($interval->i == 1) return $interval->format('a minute ago');
	if ($interval->i > 1) return $interval->format('%i minutes ago');
	return $interval->format('just now');
}

echo getHumanTimeDiff('2000-01-01') . PHP_EOL;
echo getHumanTimeDiff(date("Y-m-d H:i:s")) . PHP_EOL;
echo getHumanTimeDiff(date("Y-m-d H:i:s", time() - 60)) . PHP_EOL;
echo getHumanTimeDiff(date("Y-m-d H:i:s", time() - 120)) . PHP_EOL;
echo getHumanTimeDiff(date("Y-m-d H:i:s", time() - 60 * 60)) . PHP_EOL;
echo getHumanTimeDiff(date("Y-m-d H:i:s", time() - 60 * 60 * 24)) . PHP_EOL;
echo getHumanTimeDiff(date("Y-m-d H:i:s", time() - 60 * 60 * 24 * 2)) . PHP_EOL;

Source: https://syframework.alwaysdata.net/human-time-diff

We can also use Carbon, a simple PHP API extension for DateTime to implement different Date and Time formats.

Views: 50

Standard