MultiformeIngegno
MultiformeIngegno

Reputation: 7059

WordPress: if post time is after a specific date

I'm trying to add to this if statement another one that checks if post time is before a specific date (let's say 14th March 2014..).

<?php if (in_category('5')) {
    echo 'something'; }
?>

I tried with this but it's echoed even on posts newer than that date

<?php
    $date1 = "2014-03-14";
    $date2 = $post->post_date;
    if ( (in_category('5')) && ($date1 < $date2) ) {
        echo 'something';
    }

?>

Upvotes: 0

Views: 4205

Answers (2)

user3207595
user3207595

Reputation: 11

Thanks to Nathan, his answer worked great for me.

global $post;
$compare_date = strtotime( "2016-07-14" );
$post_date    = strtotime( $post->post_date );

if ( in_category(2) && ( $compare_date >= $post_date ) ) { 
    echo "On or before July 14."
} else { 
    echo "After July 14."
}

Upvotes: 1

Nathan Dawson
Nathan Dawson

Reputation: 19308

I'd convert your dates to timestamps first to make them easier to compare.

global $post;
$compare_date = strtotime( "2014-03-14" );
$post_date    = strtotime( $post->post_date );

if ( in_category(5) && ( $compare_date > $post_date ) ) ...

It looks like you have your operator the wrong way round as well. You wanted to check if posts are before the date. The post date would have to be smaller to be before. Also you're passing in category ID 5 as a string for some reason which I corrected in my code above.

Upvotes: 3

Related Questions