# Schedule Widgets With Start and End Dates

> Adds "Show from" and "Show until" date fields to every classic widget, so a promotion, event notice or holiday message appears and disappears on its own.

- Type: PHP
- Runs: Run everywhere
- Category: [Widgets](https://wpide.com/library/category/widgets/)
- Tags: widgets, schedule, promotions
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/schedule-widgets-by-date/

## Code

```php
add_action( 'in_widget_form', function ( $widget, $return, $instance ) {
    foreach ( array( 'wpide_show_from' => 'Show from', 'wpide_show_until' => 'Show until' ) as $key => $label ) {
        $id = $widget->get_field_id( $key );

        echo '<p><label for="' . esc_attr( $id ) . '">' . esc_html( $label ) . ':</label> <input type="datetime-local" class="widefat" id="' . esc_attr( $id ) . '" name="' . esc_attr( $widget->get_field_name( $key ) ) . '" value="' . esc_attr( isset( $instance[ $key ] ) ? $instance[ $key ] : '' ) . '" /></p>';
    }

    echo '<p class="description">Leave empty for no limit. Times use the site time zone.</p>';
}, 10, 3 );

add_filter( 'widget_update_callback', function ( $instance, $new_instance ) {
    foreach ( array( 'wpide_show_from', 'wpide_show_until' ) as $key ) {
        $value = isset( $new_instance[ $key ] ) ? sanitize_text_field( $new_instance[ $key ] ) : '';

        $instance[ $key ] = preg_match( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/', $value ) ? $value : '';
    }

    return $instance;
}, 10, 2 );

add_filter( 'widget_display_callback', function ( $instance ) {
    if ( ! is_array( $instance ) || ( empty( $instance['wpide_show_from'] ) && empty( $instance['wpide_show_until'] ) ) || is_admin() ) {
        return $instance;
    }

    $now  = current_datetime()->format( 'Y-m-d\TH:i' );
    $from = isset( $instance['wpide_show_from'] ) ? $instance['wpide_show_from'] : '';
    $till = isset( $instance['wpide_show_until'] ) ? $instance['wpide_show_until'] : '';

    // Same-format strings compare correctly as text.
    if ( ( '' !== $from && $now < $from ) || ( '' !== $till && $now >= $till ) ) {
        return false;
    }

    return $instance;
} );
```

## Notes

Times use the time zone in Settings > General; a page cache may keep showing a widget until the cache is cleared.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Schedule Widgets With Start and End Dates" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
