I was recently working on a WordPress site where the client asked for posts to disappear off the page once an event had taken place. My first point of call was looking for an appropriate WordPress Plugin. Most of these plugins however, work by either changing the category of the post or by un-publishing the post so that it becomes a draft. These did not fit the bill. I needed the post to still be filed under it’s correct category and to remain published so that it could be found in the Archives.
Because my current PHP skills are of the ‘cut & paste’ variety, I sought some help in the Sitepoint Forum. Thanks to ‘kohoutek’, I ended up using this code in my custom template:
<?php query_posts('cat=4,1'); ?> //my custom query for categories 4 & 1 <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <!-- expiry code below --> <?php $currentdate = date("Ymd"); $expirationdate = get_post_custom_values('expiration'); if (is_null($expirationdate)) { $expirestring = '30001212'; //Set future date to posts with expiry. } else { if (is_array($expirationdate)) { $expirestringarray = implode($expirationdate); } $expirestring = str_replace("/","",$expirestringarray); } //else if ( $expirestring > $currentdate ) { ?> <!--end expiry code--> <div <?php post_class() ?> id="post-<?php the_ID(); ?>"> <!-- thumbnail code below --> <?php if ( has_post_thumbnail() ) { ?> <a href="<?php the_permalink() ?>"><?php the_post_thumbnail(); ?></a> <?php } else { ?> <?php } ?> <!--end thumbnail code--> <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <p>Posted on <?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></p> <!-- shows excerpts below --> <?php global $more; $more = 0; ?> <!-- end shows excerpts code --> <?php the_content('Read the rest of this entry »'); ?> <p><?php the_tags('Tags: ', ', ', '<br />'); ?> Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit'); ?> </p> </div> <?php } ?> <?php endwhile; endif; ?>
To assign an expiry date to a post, add a custom field named ‘expiration’ and give it a value of ‘YYYYMMDD’ (year, month, day). The post will then expire on that date at midnight.
Please not that this code isn’t without it’s limitations. (So any suggestions will be warmly welcomed!) It only sets an expiry date, not time. And, as far as I can work out, it is based on Greenwich Mean Time, not the time I have set in WordPress. I would REALLY appreciate a fix for that!