← Writing

April 7, 2016

Add "xx Times ago" Function without plugin on Your WordPress Theme

Add "xx Times ago" Function without plugin on Your WordPress Theme

Today I am going to publish a PHP function for a WordPress theme to show “xx hours ago”, “xx seconds ago”, “xx minutes ago”, “xx days ago”, etc. on WordPress posts, comments, and more.

First, copy this function to your theme’s functions.php file — typically at /wp-content/themes/YOUR-THEME/functions.php:

<?
function time_ago( $type = 'post' ) {
    $d = 'comment' == $type ? 'get_comment_time' : 'get_post_time';
    return human_time_diff($d('U'), current_time('timestamp')) . " " . __('ago');
}
?>

Your function is now ready to call. It has one optional parameter — the default value is "post". Call it inside a WP loop:

<?php echo time_ago("post"); ?>

For comment type:

<?php echo time_ago("comment"); ?>

For post type (using the default):

<?php echo time_ago(); ?>

That’s all. Done!

If you have any problem, feel free to comment.

  • times ago
  • days ago
  • hours ago
  • no plugin
  • without plugin
  • Wordpress
  • wp extend
  • wp function
  • wp plugin