HowTo – WordPress Set A Post Expire Date

Filed under: Wordpress Tips

wordpress-logoDepending on the content of your website you may have posts that you need to get rid of  after a certain Date.

To do this you can set up a loop hack in your wordpress theme files that will exclude posts that have a date set in a custom field.

This will not remove the post from your database and you will need to place this loop hack in any category or index page along with your single or other theme template files that display posts that need to be controlled by date.

You should also pay close attention to how your cache plugin is deleting expired pages and manually delete pages as needed.

To Apply The Loop Hack

First open a new post and give it a name and add content.

Next below the post content area in the editor add a custom field named expiredate

In the expiredate field set the date and time that you want the post to expire in the following format Month Day Year mm/dd/yyyy 00:00:00

Once you have the expire date set for the post save it.

Editing Your Loop

To catch pages based on this custom field date you need to read it within the loop and then exclude pages from display.

If you have a custom Theme you may need to make additional changes.

if (have_posts()) :
while (have_posts()) : the_post(); ?>
$expirepostvalue = get_post_custom_values(‘expiredate’);
if (is_array($expirepostvalue)) {
$expireresults = implode($expirepostvalue);
}

$secondsbetween = strtotime($expireresults)-time();
if ( $secondsbetween > 0 ) {

// Do all the regular stuff

the_title
the_tags
the_content

}
endwhile;
endif;

This code snippet will need adjusting based on your theme and needs but the idea is that you are using  a custom field to store the expire time and then reading it back before the post is displayed.

This is very work intensive on the editor but it is one solution.

You may also want to look for a plugin that will allow you to perform this task from your add new window. To date there have been a few plugins that have attempted this task however they are somewhat dated and need rewriting.