Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.