How to set end dates for content

Usually, we want our content to display forever, but there can be times, particularly with advertorial type information that we want/need content to display at a certain time (which is easily accomplished with WordPress’ scheduling feature) but also to end at a set time.

I recently encountered this with one of my clients who has a site where they run a paid content spot, for a week at a time. The spot is not always active, and it needs to go live and come down at a set time without intervention from a site admin.

Like I said, making it go live at a set time is easy, and already built in to WordPress, but ending its display at a given time is a little trickier.

To accomplish this, I used the amazing Custom Metaboxes and Fields for WordPress. I have written about how to use this tool in more detail on WPExplorer, so I’ll skip over the setup part.

I had already set up a custom post type for this particular advertorial item, so I added a date/time picker metabox to the custom post type:

Using a custom metabox to set the end time for a WordPress post

We’ve now got a way to set what time the item should end, but we need to take that data and apply it to the theme. So in home.php, I modified my custom loop (note the use of transients) to only show this section if there are any items currently scheduled to publish (i.e. the publish date is in the past, but the end time has not yet been exceeded):

Note that in line 3, we’re getting the timestamp for the client’s time zone so that the ad ends at the correct local time, not UTC. Then in lines 7-13, we’re using the meta_query argument of WP_Query to check for items whose end time has not yet happened. The rest of the query can be configured to your own needs.

The result is the display of a single “spotlight” item for exactly one week, as we wanted. At the end of the week, either the whole section will be hidden if there is no item scheduled for the following week, or next week’s item will appear in its place.

Leave a Reply