介绍
免插件给wordpress加上历史上的今天功能,对于老站(超过1年以上)还是很不错的。今天把这个实现办法分享给大家。
代码
将以下代码添加到我们主题的function.php
文件中即可。
- //历史上的今天
- function?wp_today(){
- ????global?$wpdb;
- ????$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?h_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?5";
- ????$histtory_post?=?$wpdb->get_results($sql);
- ????if(?$histtory_post?){
- ????????foreach(?$histtory_post?as?$post?){
- ????????????$h_year?=?$post->h_year;
- ????????????$h_post_title?=?$post->post_title;
- ????????????$h_permalink?=?get_permalink(?$post->ID?);
- ????????????$h_comments?=?$post->comment_count;
- ????????????$h_post?.=?"<li><strong>$h_year:</strong> <a?href='".$h_permalink."'?title='".$h_post_title."'?target='_blank'>$h_post_title($h_comments)</a></li>";
- ????????}
- ????}
- ????if?(?$h_post?){
- ????????$result?=?"<h2>历史上的今天:</h2><ul>".$h_post."</ul>";
- ????}
- ????return?$result;
- }
- function?wp_today_auto($content){
- ????if(?is_single()?){
- ????????$content?=?$content.wp_today();
- ????}
- ????return?$content;
- }
- add_filter('the_content',?'wp_today_auto',9999);
温馨提示
以上代码默认是将历史上的今天添加到文章的最后,如果需要人工设置位置,只需要将26-32行的代码删除,然后在指定位置添加以下代码即可:
- <?php?echo?wp_today();??>
延伸拓展
插件:柳城博主的WP-Today。可自行去下载
评论