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.

  • $expired = ( ( time() - strtotime(get_the_date('Y-m-d H:i:s')) ) / DAY_IN_SECONDS ) >= 5; – Samuel Elh Jul 26 '16 at 16:15
  • 1
    @SamuelElh why not add it as an answer and explain what it is doing? – DᴀʀᴛʜVᴀᴅᴇʀ Jul 26 '16 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. – Andy Macaulay-Brook Sep 20 '16 at 12:40
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
    Up vote back for the bit I was feeling to lazy to do :-) – Andy Macaulay-Brook Jul 27 '16 at 9:27

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.