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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.