我从@moraleida获得了答案所提供的代码,并对其进行了改进,以便它可以查看发布日期,而不是服务器日期。
我还对其进行了修改,以便它可以查找该帖子每月和每天的所有帖子,并链接到它们,只要它不是显示在上面的同一个帖子ID。毕竟,既然你已经阅读了2012年1月31日的帖子,就不需要链接到自己。例如,2012年的帖子应该显示2011年的链接,2011年的帖子应该显示2012年的链接。如果你每天发布超过一次,这也是有益的。它将在当天显示这两个帖子,即使是同一年发布的。
我把它变成了一个可以变成函数的函数。php。要在模板中显示此内容,请使用<?php on_this_day(); ?>
在模板文件中。
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;
}