# "On This Day" Posts Shortcode

> Adds an [on_this_day] shortcode that lists posts published on today's date in previous years, a simple way to resurface archive content on the homepage or in a sidebar.

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: shortcodes, archives, engagement
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/on-this-day-shortcode/

## Code

```php
add_action( 'init', function () {
    add_shortcode( 'on_this_day', function ( $atts ) {
        $atts = shortcode_atts( array( 'count' => 5, 'text' => 'On this day in past years:' ), $atts, 'on_this_day' );
        $now  = current_datetime();

        $cache_key = 'wpide_otd_' . $now->format( 'Ymd' ) . '_' . (int) $atts['count'];
        $ids       = get_transient( $cache_key );
        if ( false === $ids ) {
            $ids = get_posts( array(
                'post_type'      => 'post',
                'posts_per_page' => max( 1, min( 20, (int) $atts['count'] ) ),
                'fields'         => 'ids',
                'no_found_rows'  => true,
                'date_query'     => array(
                    array( 'month' => (int) $now->format( 'n' ), 'day' => (int) $now->format( 'j' ) ),
                    array( 'before' => $now->format( 'Y' ) . '-01-01' ),
                ),
            ) );
            set_transient( $cache_key, $ids, strtotime( 'tomorrow', $now->getTimestamp() ) - $now->getTimestamp() + 60 );
        }

        if ( ! $ids ) {
            return '';
        }

        $html = '<div class="wpide-on-this-day"><p>' . esc_html( $atts['text'] ) . '</p><ul>';
        foreach ( $ids as $id ) {
            $html .= sprintf( '<li><a href="%s">%s</a> <small>(%s)</small></li>', esc_url( get_permalink( $id ) ), esc_html( get_the_title( $id ) ), esc_html( get_the_date( 'Y', $id ) ) );
        }
        return $html . '</ul></div>';
    } );
} );
```

## Notes

Shows nothing on days with no matches; add text="..." to change the intro line. The list is cached until midnight.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find ""On This Day" Posts Shortcode" 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/
