WordPress 可以通过显示相关文章来增加页面浏览量,另一种方法就是显示历史上的今天,可以看到更早之前同一天更新过哪些文章,原理就是通过查询数据库里日期和今天 一样的文章,并用 add_filter 函数把 HTML 代码更新到文章内容变量 the_content 里,荒岛本次带来 WordPress 添加历史上的今天教程,只要将下面的代码添加到主题的「functions.php」文件即可。
// 荒岛一座藏有宝藏的小岛
function hd_today(){
global $wpdb;
$today_post = '';
$result = '';
$post_year = get_the_time('Y');
$post_month = get_the_time('m');
$post_day = get_the_time('j');
$sql = "select ID, year(post_date_gmt) as today_year, post_title, comment_count FROM
$wpdb->posts WHERE post_password = '' AND post_type = 'post' AND post_status = 'publish'
AND year(post_date_gmt)!='$post_year' AND month(post_date_gmt)='$post_month' AND day(post_date_gmt)='$post_day'
order by post_date_gmt DESC limit 7";
$histtory_post = $wpdb->get_results($sql);
if( $histtory_post ){
foreach( $histtory_post as $post ){
$today_year = $post->today_year;
$today_post_title = $post->post_title;
$today_permalink = get_permalink( $post->ID );
$today_post .= '<li><a href="'.$today_permalink.'" target="_blank"><span>'.$today_year.'</span>'.$today_post_title.'</a></li>';
}
}
if ( $today_post ){
$result = '<div class="begin-today"><fieldset><legend><h5>'. sprintf(__( '历史上的今天', 'begin' )) .'</h5></legend><div class="today-date"><div class="today-m">'.get_the_date( 'F' ).'</div><div class="today-d">'.get_the_date( 'j' ).'</div></div><ul>'.$today_post.'</ul></fieldset></div>';
}else{
$result = '<div class="begin-today"><fieldset><legend><h5>'. sprintf(__( '历史上的今天', 'begin' )) .'</h5></legend><div class="today-date"><div class="today-m">'.get_the_date( 'F' ).'</div><div class="today-d">'.get_the_date( 'j' ).'</div></div><div><span class="nfhd">'.get_the_time('Y').'</span> 荒岛宝藏 即将发布 敬请期待...</div></fieldset></div>';
}
return $result;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。