How to Display a Warning If a WordPress Post is Older Than a Set Time

Home » Snippets » How to Display a Warning If a WordPress Post is Older Than a Set Time
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Have you ever wanted to display a notice on your WordPress posts that indicates when the article was published? Do you want to alert readers when they’re reading content that might be outdated? One way to keep your readers informed is by adding an "older than" notice to posts of a certain age. This can provide your audience with context, especially if you blog about rapidly-changing topics. In this article, we’ll guide you step-by-step on how to set up such a feature in WordPress.

					function wpturbo_is_post_older_than($days) {
    global $post;
    $days_ago = date('Ymd', strtotime("-{$days} days"));
    $post_date = get_the_date('Ymd', $post->ID);
    return ( $post_date < $days_ago );
}
				

Before going step by step through the code it is necessary to understand what this code snippet does: it checks if a WordPress post is older than a set number of days.

The code defines a new function called wpturbo_is_post_older_than($days). It takes in one parameter - $days, which specifies the number of days to check against.

function wpturbo_is_post_older_than($days) {

Inside the function, we make use of the $post global variable. This built-in WordPress object contains information about the current post, including when it was published.

global $post;

The variable $days_ago is then created, which contains the formatted date for the day $days ago from the current date. The date PHP function is used with the strtotime PHP function to adjust the current date. 'Ymd' in the date function specifies the format of the date.

$days_ago = date('Ymd', strtotime("-{$days} days"));

Next, we have the $post_date variable. The get_the_date('Ymd', $post->ID); function fetches the published date of the current post and formats it to 'Ymd'.

$post_date = get_the_date('Ymd', $post->ID);

The last line of code in this function compares the $post_date (date when the post was published) with $days_ago (date $days before today) and returns TRUE if $post_date is less than $days_ago, i.e., the post is older than specified $days. Otherwise, it returns FALSE.

return ( $post_date < $days_ago );
}

In essence, this function can be used in a theme or plugin to perform actions on posts that are older than a certain number of days.

Register an account to save your snippets or go Pro to get more features.