April 9, 2014 / IST / How-to Guides, Web Development.

This trick comes becomes very useful when you are running a contest because you might be posting information such as clues or hints that you don’t want to stay up for ever. Instead of manually removing the article, you can just make it expire automatically. It also works if you have a product that you are offering a discount on. You posted it on your blog, but you don’t want that discount to stay on your blog after its over. So you can remove it automatically with bellow code.

post-expiration-wordpress-pointerbrain

First, you have to make a Custom field named “expiration”. you can use custom fields when writing a post to set an expiration date. After writing post expiration date selecting by the key “expiration”  from Custom Field. Here You have to fill date in correct format: mm/dd/yyyy 00:00:00.  Date format tow thing. Date and time with space between.

Now, all you need to do is replace your WordPress Loop with this code in single.php  or in all php page in template:

<?php
if (have_posts()) :
while (have_posts()) : the_post();
$expirationtime = get_post_custom_values('expiration');
if (is_array($expirationtime)) {
$expirestring = implode($expirationtime);
}

$secondsbetween = strtotime($expirestring)-time();
if ( $secondsbetween > 0 ) {
// For example…
the_title();
the_content();
}
endwhile;
endif;
?>

 Read also: How to use Custom Field

Now this hack does not remove or unpublish the article instead it just excludes the article from being displayed in the loop.