Make a Widget Expire

I had a thought today. Have you ever visited a website one noticed an item about an upcoming event? And then you look and see that the event happened a few days (or months) ago?

That can happen to anyone. If the event is a big deal, then perhaps updating your site the day after the event isn’t a priority as you rest up. Or, maybe you just forget.

So why not have things like widgets expire? It is easy enough to do with a hack if it is your widget. Here is an example of a simple text widget that expires at a specific time. After that time, it simply doesn’t display at all. And you can set this time using any strtotime string, like 2018-12-31.

add_action('widgets_init', 'add_wpwidget_expire');

function add_wpwidget_expire() {

class wpwidget_expire extends WP_Widget {
	function __construct() {
		$options = array('description' => 'Display text, expire after specific date.');
		parent::__construct('wpwidget_expire', 'Expire Text', $options);

	function widget($args, $instance) {
		// if the time is after the expiration time, then don't display anything at all
		if (strtotime($instance['expires']) <= time()) return;
		$title = apply_filters('widget_title', $instance['title']);
		if (!empty($title)) {

	function form($instance) {
		$title = esc_attr($instance['title']);
		if ($title == '') $title = 'Text';
		$id = $this->get_field_id('title');
		$name = $this->get_field_name('title');
		echo("<p><label for=\"$id\">Title:</label><input class=\"widefat\" id=\"$id\" name=\"$name\" type=\"text\" value=\"$title\" /></p>");

		$expires = esc_attr($instance['expires']);
		if ($expires == '') $expires = date("Y-m-d", strtotime('+1 month'));
		$id = $this->get_field_id('expires');
		$name = $this->get_field_name('expires');
		echo("<p><label for=\"$id\">Expiration Date:</label><input class=\"widefat\" id=\"$id\" name=\"$name\" type=\"text\" value=\"$expires\" /></p>");

		$text = esc_textarea($instance['text']);
		if ($text == '') $text = '';
		$id = $this->get_field_id('text');
		$name = $this->get_field_name('text');
		echo("<p><label for=\"$id\">Text:</label><textarea class=\"widefat\" rows=\"16\" cols=\"20\" id=\"<?php echo $id\" name=\"$name\">$text</textarea></p>");


The only real innovation here is the very first line of the widget function. That’s what checks the time against the server time and quits the function without doing anything. Then in the form function, there is an extra field to allow entry of this value.

Leave a Reply

Your email address will not be published. Required fields are marked *