X

How to Add Time Stamp on WordPress Posts and Comments

Snippets by IsItWP

Are you looking for a way to add Facebook like “Time Ago” time stamp on WordPress posts and comments? While there’s probably a plugin for this, we have created a quick code snippet that you can use to add time stamp on WordPress posts and comments.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:


function time_stamp($from){
	$cmt_date = $from;
	$from = strtotime($from);
	if ( empty($to) )
		$to = time();
	$diff = (int) abs($to - $from);
	if($diff <= 1){
		$since = '1 second';
	} else if($diff <= 60 ){
		$since = sprintf(_n('%s second', '%s seconds', $diff), $diff);
	} else if ($diff <= 3600) {
		$mins = round($diff / 60);
		if ($mins <= 1) {
			$mins = 1;
		}
		/* translators: min=minute */
		$since = sprintf(_n('about %s min', '%s mins', $mins), $mins);
	} else if ( ($diff <= 86400) && ($diff > 3600)) {
		$hours = round($diff / 3600);
		if ($hours <= 1) {
			$hours = 1;
		}
		$since = sprintf(_n('about %s hour', '%s hours', $hours), $hours);
	} elseif ($diff >= 86400 && $diff <= 86400*2 ) {
		$days = round($diff / 86400);
		if ($days <= 1) {
			$days = 1;
		}
		$since = sprintf(_n('%s day', '%s days', $days), $days);
	} else {
		return date('M d at h:i a',$from);
	}
	return $since . ' ago';
}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 19 best WordPress plugins for photographers and how to easily create a multilingual WordPress website.

Comments   Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!