I’m working with this code snippet for an “on this day” type post. However it is only showing 1 year in the past. I’m looking to automate this so it shows on this day in 2009, 2010, 2011… and as the years advance, keep these years showing. With the way it’s written as a -1, -2, it will be a dynamic “year ago” rather than a static “in 2009”.
Is there a way to automate this to go back 2, 3 4 years without having to duplicate the code for (-2, -3, -4, etc)?
function on_this_day() {
$on_this_day = get_posts('year='.(date('Y')-1).'&monthnum='.date('n').'&day='.date('j'));
if( $on_this_day ) {
echo '<a class="on-this-day" href="'.get_day_link( (date('Y')-1), date('m'), date('d')).'" title="On This Day in '.(date('Y')-1).'">';
echo 'On this day in '.(date('Y')-1);
echo '</a>';
} else {
echo '<span class="on-this-day-none">'.'On this day in <span>'.(date('Y')-1).'</span></span>';
}
Adapted from the Codex, tweaking WP_Query to get all years before this.
Untested, but should work.
UPDATE
Updated code with the complete loop. It should now output a list of links for the years past, leaving out the years with no posts for that date;
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.