In this post, you’ll learn how you can change WordPress date to the ‘time ago’ format programmatically with the help of some filter hooks.
The script:
Add this is the script at the bottom of the functions.php file:
/**
* depending on your theme, you may only use time or date filters. You can remove unnecessary hooks.
*/
add_filter( 'get_the_date', 'timeAgoFormat' );
add_filter( 'the_date', 'timeAgoFormat' );
add_filter( 'get_the_time', 'timeAgoFormat' );
add_filter( 'the_time', 'timeAgoFormat' );
function timeAgoFormat( $publish_time ) {
// convert publish date into a Unix timestamp (e.g. June 5, 2022 => 1654387200... ms)
$publish_time = strtotime( $publish_time );
/**
* Get the difference between the current time and the publish time ($publish_time)
* Return the result in a human readable format ("1 hour", "2 days", "5 mins", ...)
*/
return human_time_diff( $publish_time, current_time( 'timestamp' ) ).' '.__( 'ago' );
}
Conclusion:
With the help of some hooks and date functions, you’ll be able to change publish date from a regular date format into the better “time ago” format. Good luck!