wordpress代码实现历史上的今天功能

2020年01月2日21:13:26 发表评论 热度330 ℃

使用wordpress时间久了就想增加些个性功能,感觉柳城博主的这个wp_today功能还是蛮不错的,及个性化自己的网站,同时对于网站的seo排名也是小有帮助,比起常规的相关文章插件也更能吸引人吧,但是插件多了毕竟影响速度,所以,也在网上找了一个代码版的。

wordpress代码实现历史上的今天功能

以下是基本的代码可按自己喜欢的样式修改。本文作为对博客修改的一次记录,同时也希望帮助到那些需要的站长们。按步骤将以下代码添加到function.php文件末尾即可。

  1. //历史上的今天,代码来自柳城博主的 WP-Today 插件
  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. function wp_today_auto($content){
  2.         if( is_single() ){
  3.             $content = $content.wp_today();
  4.         }
  5.         return $content;
  6.     }
  7.     add_filter('the_content', 'wp_today_auto',9999);

然后在需要显示的位置用下面函数调用即可。

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

瓜皮猪

发表评论

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