0

I use the following code in my template.

<?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?>

It shows like 2 days ago, 20 days ago, 90 days ago.

Is there a way to show 1 week ago instead of 7 days ago, 1 month ago instead of 30 days ago, 1 year ago instead of 365 days ago?

Thanks

1

As far as I know that's as deep as wordpress can go, you will have to use php to get it into weeks/months/etc.

You have 2 options:

Use human_time_diff and create a function that just calculates the differences(pretty easy to figure out 7 days = 1 week, etc). I would honestly not use human_time_diff though and use strtotime() with this method instead.

The other option is to use the DateTime and DateInterval objects in php 5.3 +. You can see an example here ( second answer), https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php

1

You can see the current function in wp-includes/formatting.php and, as you allude to, only breaks down to minutes, then hours, then days.

One suggestion is to then look at Core Trac and see if there are already plans to change this. A quick search for human_time_diff turned up ticket #9272.

Unfortunately it seems to have stalled, you can certainly join in and reboot the conversation or provide your own code, use cases, testing results, etc.

Or, you can simply create your own function (copy the existing as a starting point) and wrap the timestamps accordingly.

0

Since I just tested this code, on a blog where I have many post excerpts:

echo $daysago = human_time_diff( get_the_date( 'U', $pid ), current_time('timestamp'));

I get the correct results:

3 days
1 week
2 weeks
3 weeks
1 month
2 months
6 months

This is so according to the documentation:

Please check out that I also use the $pid representing the post ID. Looks like the function improved over time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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