How to compare publish posts based on years?

All we need is an easy explanation of the problem, so here it is.

I need help with my code. I found this code from "https://wordpress.stackexchange.com/questions/36184/how-can-i-put-posted-x-minutes-ago-on-my-posts" on how to display the publish date as xx seconds/hours ago. I’m having problems comparing years on a published post where it shows the year if the published years don’t match.

function k99_relative_time() { 
$post_date = get_the_time('U');
$delta = time() - $post_date;
if ( $delta < 60 ) {
    echo strval(round(($delta))), ' seconds ago';
}
elseif ($delta > 60 && $delta < 120){
    echo '1 minute ago';
}
elseif ($delta > 120 && $delta < (60*60)){
    echo strval(round(($delta/60),0)), ' minutes ago';
}
elseif ($delta > (60*60) && $delta < (120*60)){
    echo '1 hour ago';
}
elseif ($delta > (120*60) && $delta < (24*60*60)){
    echo strval(round(($delta/3600),0)), ' hours ago';
}
else {
    // code with problems
    // show year in publish date if the years of post don't match
    if (get_the_time('Y') !== get_the_time('Y')) {
        echo the_time('M. d, Y');
    // don't show year if they do match
    } else {
        echo the_time('M. d');
    }
}
}

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You have the following line:

if (get_the_time('Y') !== get_the_time('Y')) {

If compares 2 equal values.
So those will never differ.

Did you mean something like the following?

if (get_the_time('Y') !== date('Y')) {

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply