Check If Post Was Published More Than 6 Months Ago Using get_the_date

Inside my content-single template, I have a conditional check that displays text based on how old the post is. The idea is to inform visitors that they might be reading “old” news.

Problem is; the 6+ months old text is displayed on posts that are only days old, and I do not understand why.

This is the code I am using:

<?php
    
    if ( strtotime( get_the_date() ) < strtotime( '-1 year' ) ) { ?>

        <span class="old-post"> 6+ months old </span>&nbsp;/&nbsp;
        
        <?php 
    } 

?>

This is the format I am using in WP admin for date and time:

l the jS of F @ H:i

Please help me understand how to fix this.

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

The problem is that your date format is not a standard format that strtotime() understands. Instead just use get_the_date() with the format set to 'U', which returns the timestamp, and compare that to strtotime( '-1 year' ):

if ( get_the_date( 'U' ) < strtotime( '-1 year' ) ) {

}

Method 2

By using below code, you can check if Post Was published more than 6 Months ago using get_the_date.

place below code inside content-single template, It inform visitors that they are reading “old” news which is plublished 6+ months old.

# get last 6 month date from current date
$last_sixth_month_date = strtotime("-6 month"); 

# publish date
$post_poblish_date = strtotime( get_the_date() );

# get difference from two dates
$year1 = date('Y', $last_sixth_month_date);
$year2 = date('Y', $post_poblish_date);
$month1 = date('m', $last_sixth_month_date);
$month2 = date('m', $post_poblish_date);
$month_diffrence = (($year2 - $year1) * 12) + ($month2 - $month1);

if($month_diffrence < 0 )
{
    # check difference between date is 6 or more than 6
    if(abs($month_diffrence) >= 6 )
    {
        echo  '<span class="old-post"> 6+ months old </span>&nbsp;/&nbsp';
    }
}


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