Modify human_time_diff() to shorten “days” to “d” and “hours” to “h” etc

I’m using the function echo time_ago() that displays the time like this:

5 days ago what’s the best way to change it to 5d ago ?

Read More

My research led me to human_time_diff() function located in “formatting.php” So I have tried directly editing the function located at /wp-includes/formatting.php but when I change “hours” to “h” and so on… it goes crazy and gives me errors. I know modifying the core isn’t the best way, so any ideas? Thank you.

Related posts

Leave a Reply

1 comment

  1. There is no filter for output of that function. You can fork (copy/rename/edit) it or add wrapper that will replace strings in output like this:

    function short_time_diff( $from, $to = '' ) {
    
        $diff = human_time_diff($from,$to);
    
        $replace = array(
            'hour'  => 'h',
            'hours' => 'h',
            'day'   => 'd',
            'days'  => 'd',
        );
    
        return strtr($diff,$replace);
    }
    

    PS afterthought – actually strings are localized so there is translation filter to use… But stuff to replace is to generic and that will risk breaking it elsewhere.

    UPDATE

    Since WP 4.0 there is a filter available for human_time_diff:

    add_filter( 'human_time_diff', function($since, $diff, $from, $to) {
    
        $replace = array(
            'hour'  => 'h',
            'hours' => 'h',
            'day'   => 'd',
            'days'  => 'd',
        );
    
        return strtr($since, $replace);
    
    }, 10, 4 );