I took the code provided by the answer from @moraleida and improved it so that it would look at the post dates, and not the server dates.
I also modified it so that it would look for all posts on that post Month and Day, and link to them as long as it's not the same post ID that's being displayed on. Afterall, since you're already reading the post from Jan 31, 2012, no need to link to itself. For example, the 2012 post should show a 2011 link, and a 2011 post should show the 2012 link. This is also beneficial if you have posted more than 1 time per day. It will show both posts on that day, even if it's from the same year.
I turned this into a function which can go into functions.php. To display this in your template, use <?php on_this_day(); ?> in your template file.
function on_this_day(){
$on_this_day = array(
// Build the array using post date, and omit the year
'monthnum' => get_the_date('n'),
'day' => get_the_date('j')
);
add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $on_this_day );
remove_filter( 'posts_where', 'filter_where' );
if( $query->have_posts() ) {
// Uncomment this next line to echo an On this day prefix to the years.
// echo "On this day in ";
$postYear = get_the_date('Y');
while ($query->have_posts()) {
$query->the_post();
$year = get_the_time('Y');
$queryYear = get_the_date('Y');
$month = get_the_time('m');
$day = get_the_time('d');
if ($queryYear == $postYear) {
// I use permalinks to link to. If you'd rather link to the day archive list, use get_day_link($year, $month, $day) instead of get_permalink.
// This line compares the query year to the post year. If it's the same year, then add "Also from" so that it doesn't look like a duplicate link.
echo '<a class="on-this-day" href="'.get_permalink($query->ID).'" title="On this day in '.$year.' - '.get_the_title().'">Also from '.$year.' - '.get_the_title().'</a><br> ';
} else {
echo '<a class="on-this-day" href="'.get_permalink($query->ID).'" title="On this day in '.$year.' - '.get_the_title().'">'.$year.' - '.get_the_title().'</a><br> ';
}
}
// Reset post data so it displays the original post.
wp_reset_postdata();
} else {
// No posts to show
echo "No Historical Posts On This Day";
}
}
// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
// Posts for all years before the current post date.
//$where .= " AND post_date < '" . get_the_date('Y-m-d') . "'";
// Filter on post ID instead
$where .= " AND ID <> '" . get_the_ID() . "'";
return $where;
}