WordPress教程:为站点添加历史上的今天功能

  • A+
所属分类:wordpress

在许多网站上看到这个功能,便找了下,收集到这里,来分享给大家,这个是纯代码。因为WordPress插件用多了会拖慢网页打开速度,所以收集的是纯代码。

显示的是网站的历史上的今天,所以,使用本功能的朋友们,需要网站开启时间大于1年,才会有效果。

WordPress教程:为站点添加历史上的今天功能

纯代码实现历史上的今天这个功能,还是可以的。我们只需要将以下代码添加到我们主题的function.php文件中即可实现在文章最后添加历史上的今天这个功能。

  1. //历史上的今天
  2. function wp_today(){
  3.     global $wpdb;
  4.     $post_year = get_the_time('Y');
  5.     $post_month = get_the_time('m');
  6.     $post_day = get_the_time('j');
  7.     $sql = "select ID, year(post_date_gmt) as h_year, post_title, comment_count FROM 
  8.             $wpdb->posts WHERE post_password = '' AND post_type = 'post' AND post_status = 'publish'
  9.             AND year(post_date_gmt)!='$post_year' AND month(post_date_gmt)='$post_month' AND day(post_date_gmt)='$post_day'
  10.             order by post_date_gmt DESC limit 5";
  11.     $histtory_post = $wpdb->get_results($sql);
  12.     if$histtory_post ){
  13.         foreach$histtory_post as $post ){
  14.             $h_year = $post->h_year;
  15.             $h_post_title = $post->post_title;
  16.             $h_permalink = get_permalink( $post->ID );
  17.             $h_comments = $post->comment_count;
  18.             $h_post .= "<li><strong>$h_year:</strong>&nbsp;&nbsp;<a href='".$h_permalink."' title='".$h_post_title."' target='_blank'>$h_post_title($h_comments)</a></li>";
  19.         }
  20.     }
  21.     if ( $h_post ){
  22.         $result = "<h2>历史上的今天:</h2><ul>".$h_post."</ul>";
  23.     }
  24.     return $result;
  25. }
  26. function wp_today_auto($content){
  27.     if( is_single() ){
  28.         $content = $content.wp_today();
  29.     }
  30.     return $content;
  31. }
  32. add_filter('the_content', 'wp_today_auto',9999);

温馨提示:

1、以上代码默认是将历史上的今天添加到文章的最后,如果需要人工设置位置,只需要将29-35行的代码删除,然后在指定位置添加以下代码即可:

  1. <?php echo wp_today(); ?>

2、具体的CSS样式大家自行调整即可。

 

注:代码来自柳城博主的WP-Today插件,不想用代码的朋友也可以用这个插件。

  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: