Site logo

Archived topic

Showing "Time Ago" Properly

1 reply · Started by BK on June 5, 2020

Viewing posts 1–2 of 2

Hi,

I am having issues showing the post date with human_time_diff. I want to do this without a plugin, directly in the child theme & only show it if the post date is up to, and including, 7 days old.

Here is my code so far:

function time_ago_date( $the_date ) {
    $currentTime = current_time('timestamp');
    $postTime = get_the_time('U');
    if ((($currentTime - $postTime) / 60 / 60 / 24) > 8) {
        return sprintf('%1$s',
            get_the_date('F j, Y'));
    } else {
        return sprintf('%1$s ago',
            human_time_diff( get_the_time('U'), current_time('timestamp') ));
    }
}
add_filter( 'get_the_date', 'time_ago_date', 10, 1 );

The issues are:
- If the post date is older than 7 days, it must just have default behavior. So I just try to output the date, but this code doesn't work. The page keeps loading and won't load.
- If the post date is newer than 7 days, it must show the human_time_diff. It works, but the datetime attribute for the <time> element also shows the human_time_diff instead of the valid default behavior like "2020-06-04T03:04:00+02:00"
So I want this part to show default behavior as well, even though the post is less than 7 days old. The text for the reader must be human_time_diff only.

Any help to accomplish this (perhaps more elegantly) would be appreciated!

Here is the desired HTML result (examples):
Post is less than 7 days old:
<time class="entry-date published" datetime="2020-06-04T03:04:00+02:00">2 days ago</time>

Post is more than 7 days old:
<time class="entry-date published" datetime="2020-06-04T03:04:00+02:00">June 4, 2020</time>

Thanks

Hi there,

I don't have a lot of experience with this. However, this kind of question is perfect for a site like this: https://wordpress.stackexchange.com/

Someone with more experience with the date functions should be able to spot the issue quite quickly.

Thanks! :)

This archived topic is closed to new replies.