skip to Main Content

Converting Timestamp into a time ago in WordPress.


How we can display the published date into a time ago like ‘a second ago’, ‘a minute ago’, ‘days ago’, ‘a month ago’, ‘a year ago’ in WordPress. On this article, we will see how to convert the timestamp into a time ago. So let’s see how we can change the published time on WordPress.

So, first of all, open your active theme and find the “functions.php” file from the active theme. then after add the below code in the “functions.php” file as it is.

function converElapsedTime( $datetime, $full = false )
{
    $now = new DateTime;
    $then = new DateTime( $datetime );
    $diff = (array) $now->diff( $then );

    $diff['w']  = floor( $diff['d'] / 7 );
    $diff['d'] -= $diff['w'] * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );

    foreach( $string as $k => & $v )
    {
        if ( $diff[$k] )
        {
            $v = $diff[$k] . ' ' . $v .( $diff[$k] > 1 ? 's' : '' );
        }
        else
        {
            unset( $string[$k] );
        }
    }

    if ( ! $full ) $string = array_slice( $string, 0, 1 );
    return $string ? implode( ', ', $string ) . ' ago' : 'just now';
}

// Our filter callback function
function thecodingstuffDateago( $the_date, $d, $post ) {
	$date = date( 'Y-m-d h:i:s', strtotime( $the_date ) );
	return converElapsedTime($date);
}
add_action( 'get_the_date', 'thecodingstuffDateago',10,3);
add_action( 'the_date', 'thecodingstuffDateago',10,3);

function thecodingstuffTimeago( $the_date, $d ) {
	$date = date( 'Y-m-d h:i:s', strtotime( $the_date ) );
	return converElapsedTime($date);
}
add_action( 'the_time', 'thecodingstuffTimeago',10,3,2);
add_action( 'get_the_time', 'thecodingstuffTimeago',10,3,2);

We have to add the two filter for the date first “get_the_date” and “the_date” and the second filter is for the time “the_time” and “get_the_time” for filter the date and displays the time like a time ago.

Just add the above code and check your WordPress listing and detail page the time is changed or not.

If you face any issue after using above code write a comment below.

Saroj

I am a web designer and developer part-time blogger. Write something on some free time. Find my every day thought here :)

Leave a Reply

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

Back To Top