On this day PHP code

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>';
}

2 Answers
2

Adapted from the Codex, tweaking WP_Query to get all years before this.

Untested, but should work.

$on_this_day = array(
    // remove the year from the first query array
    'monthnum' => date('n'),
    'day' => date('j');
);


// Create a new filtering function that will add our where clause to the query
function filter_where( $where="" ) {
    // posts for all years before this year
    $where .= " AND post_date < " . date('Y');
    return $where;
}

add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $on_this_day );
remove_filter( 'posts_where', 'filter_where' );

if( $query->have_posts() ) : while ($query->have_posts()) : $query->the_post();
    $year = get_the_time('Y'); 
    $month = get_the_time('m'); 
    $day = get_the_time('d');            
    echo '<a class="on-this-day" href="'.get_day_link($year, $month, $day).'" title="On This Day in '.$year.'">';
    echo 'On this day in '.$year;
    echo '</a>';

endwhile;
endif;

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;

Leave a Comment