0

On my WordPress site, I am using the human time difference for the post date. If you have a post that was posted 59 minutes ago or under it appears as posted 1 min ago, 5 mins ago, or posted 35 mins ago. Is there a way that I can change mins to minutes?

This is the code I have.

<div class="front-page-date">
    <?php 
        echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; 
    ?>
</div>

2 Answers 2

3

You can do:

echo str_replace('mins', 'minutes', human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago');

Update:

The same using filter as suggested:

add_filter('human_time_diff', 'new_human_time_diff', 10, 2);
function new_human_time_diff($from, $to) {

    // remove filter to prevent the loop
    remove_filter('human_time_diff', 'new_human_time_diff');
    $timediff = str_replace('mins', 'minutes', human_time_diff($from, $to) . ' ago');

    // restore the filter
    add_filter( 'human_time_diff', 'new_human_time_diff', 10, 2);

    return $timediff;
}

echo human_time_diff(get_the_time('U'), current_time('timestamp'));
4
  • If you use the 'human_time_diff' filter, you'll only need to run str_replace() in one place instead of as part of the function call, if you're using it in more than one template. Jun 17, 2017 at 3:35
  • The filter callback takes different parameters than the function, so you need to check and return the string as the first parameter. Check developer.wordpress.org/reference/hooks/human_time_diff for the args list and usage. Jun 17, 2017 at 20:07
  • @morganestes yeah, I know but somehow it still works this way it is done above, but I will check why :)
    – Picard
    Jun 19, 2017 at 7:59
  • it works because you're returning the string result of human_time_diff(), which is the value that 'human_time_diff' filter changes. The side effect is that you're accidentally returning the right value, and using more function calls and filter stack modifications than needed. Jul 9, 2017 at 22:39
1

This is a good use of the human_time_diff filter, which lets you use your function call as usual, then changes the "mins" to "minutes" on the fly. No need to change your existing code or modify filter use; use string replacement in the filter callback after the time diff string is created by core.

function wpse_time_diff_mins( $since, $diff, $from, $to ) { 
    return str_replace( 'mins', 'minutes', $since );
}

add_filter( 'human_time_diff', 'wpse_time_diff_mins', 10, 4 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.