If X Amount of Time Has Passed Since Post Was Published, Do Something

if ( human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ) < strtotime( '7 days' ) ) {
    echo 'New!';
}

I’ve also tried:

if ( get_the_date( 'U' ) > strtotime( '-7 days' ) )
if ( get_the_date( 'U' ) < strtotime( '-7 days' ) )
if ( get_the_date( 'U' ) > strtotime( '7 days' ) )
if ( get_the_date( 'U' ) < strtotime( '7 days' ) )
if ( human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ) > strtotime( '-7 days' ) )
if ( human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ) < strtotime( '-7 days' ) )
if ( human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ) > strtotime( '7 days' ) )
if ( human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ) < strtotime( '7 days' ) )

The basic idea is if a blog post is still less than 7 days old, it’s still considered new.

I’m working within the loop, but perhaps my logic is wrong?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

What the current code does

human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) )

produces the time between when the post is published and the current time as a human readable string such as '6 days'. Meanwhile, strtotime( '7 days' ) retrieves a integer timestamp representing 7 days after this moment, e.g. 1625673951.

With that in mind, we can consider your comparison expression,

human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ) < strtotime( '7 days' )

to evaluate as something similar to

'6 days' < 1625673951

In this comparison, PHP tries it’s best to convert the string into an integer so it can compare it to the timestamp, and in this case '6 days' is cast as the integer 6.

A solution

One of the easiest ways to compare two dates is to just compare their integer timestamps. Here, we can compare if the post’s timestamp is greater than the timestamp of the time 7 days before this moment, indicating that it was published within the last week:

if( get_the_time( 'U' ) > strtotime( '-7 days' ) )


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x