2

I want to create a code snippet for expiration of post after x days from the post published date, I tried with this code but I always displays the true condition, what am I doing wrong?

$pfx_date       = get_the_date('d/m/Y');
$datacorrente   = date('d/m/Y', strtotime("-5 days"));

if ( $pfx_date <= $datacorrente ) { 
    echo 'post expired'; 
} else { 
    echo 'post open'; 
}

"-5 days" is the x days variable after the post is expired.

3
  • $expired = ( ( time() - strtotime(get_the_date('Y-m-d H:i:s')) ) / DAY_IN_SECONDS ) >= 5;
    – Ismail
    Jul 26, 2016 at 16:15
  • 1
    @SamuelElh why not add it as an answer and explain what it is doing?
    – user9447
    Jul 26, 2016 at 17:22
  • If either of our answers helped you solve this then please do accept one. @SamuelElh 's is better and fuller than mine. Sep 20, 2016 at 12:40

2 Answers 2

2

You're comparing strings. For dates this will only ever work out if you use a yyyymmdd format or similar.

1

Up-voting Andy's answer, you should be comparing integers to get this working. strtotime() can turn any string to the time integer, which will be compared later to tell the difference and how many seconds passed until now ( time() ). Something like follows:

$expired = ( ( time() - strtotime(get_the_date('Y-m-d H:i:s')) ) / DAY_IN_SECONDS ) >= 5;
if ( $expired ) { 
    echo 'post expired'; 
} else { 
    echo 'post open'; 
}

Hope that helps.

1
  • 1
    Up vote back for the bit I was feeling to lazy to do :-) Jul 27, 2016 at 9:27

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.