Best Softwares, Technology and Web Development Tutorials

web designing and web development tutorials in English and Urdu. especially WordPress, Node js, MongoDB, Mean Stack, Full Stack development tutorials, basic to advance HTML css and javascript tutorials.

Subscribe to Our Youtube Channel



Tuesday, 5 January 2016

Set An Expiration Time For Posts

The problem. Sometimes (for example, if you’re running a contest), you want to be able to publish a post and then automatically stop displaying it after a certain date. This may seem quite hard to do but in fact is not, using the
power of custom fields.
The solution. Edit your theme and replace your current WordPress loop with this “hacked” loop: view plaincopy to clipboardprint?

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_excerpt();
} endwhile;
endif; ?>

To create a post set to expire at a certain date and time, just create a custom field. Specify expirationas a key and your date and time as a value (with the format mm/dd/yyyy 00:00:00). The post will not show up after the time on that stamp.
Code explanation. This code is simply a custom WordPress loop that automatically looks to see if a custom field called expiration is present. If one is, its value is compared to the current date and time. If the current date and time is equal to or earlier than the value of the custom expiration field, then the post is not displayed.
Note that this code does not remove or unpublish your post, but just prevents it from being displayed in the loop.

No comments:

Post a Comment