"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.
Opens WPIDE on
Code
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 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.