I’ve been blogging on and off since 2006. A lot can change in 15 years! Especially in the tech world, information can get out-of-date fast, but that doesn’t mean it should be unpublished. Historical information can be useful for all sorts of reasons. If you ever need to google an error message from a client’s ancient, never-updated CMS, you’ll be thankful for the person who ran into the same issue ten years ago and blogged about it. Still, it’s good practice to let readers know a post is old.
A Warning Can Help Avoid Confusion
When we’re searching for something in a hurry, we don’t always check the post date. On our own posts, as a courtesy to readers, we can show an extra message highlighting the advanced age of the post. For example:
You can add a warning manually, but on a blog with hundreds of posts, automating this can save a lot of time. A dynamic warning can also make the message more useful. For example, in the message above, the number in “12 years ago” will change as the post ages.
Code to Add a Message to Old Wordpress Posts
You could add this code to your theme’s functions.php file or through a code snippets plugin. I also have an example on Github showing how to make a standalone utility plugin with this code.
/**
* Add warning message to old posts
* @author Tristan Mason <tristanmason.com> */
add_filter( 'the_content', 'tm_old_post_warning' );
function tm_old_post_warning( $content ) {
// Show only posts of any type, but not pages or archives
if ( is_single() ) {
// Set the minumum post age in years for the warning to appear
$years = (int) 6;
$offset = $years*365*24*60*60; // Offset in seconds
$post_age = round( ( date('U') - get_post_time() )/60/60/24/365) ; // Find post age to the nearest year
// Set the warning message
$warning = 'Heads up! This post is about ' . $post_age . ' years old.';
// Build the output
$output = '<div class="tm-old-post-warning">';
$output .= $warning;
$output .= '</div>';
// If the current post is older than $years, add warning before the post content
if ( get_post_time() < ( date('U') - $offset ) ) {
return $output . $content;
} else {
// Exit if not an old post
return $content;
}
} else {
// Exit if not a single post
return $content;
}
}
To style the message, add CSS styles for the class .tm-old-post-warning
to Appearance > Customize > Additional CSS. Or you can enqueue inline styles for it like this:
add_action( 'wp_enqueue_scripts', 'tm_old_post_warning_styles' );
function tm_old_post_warning_styles() {
// Change these styles to match your site
$css = '
.tm-old-post-warning {
padding: 4px 8px;
background: #eee;
display: inline-block;
border-radius: 5px;
margin-bottom: 1rem;
}';
wp_register_style( 'tm-old-post-warning', false );
wp_enqueue_style( 'tm-old-post-warning' );
wp_add_inline_style( 'tm-old-post-warning', $css );
}
Check out the standalone plugin example on GitHub: