欢迎光临
请一秒记住我们的网址:www.xinfangs.com !

如何为WordPress文章添加历史上的今天列表

如何为WordPress文章添加历史上的今天列表

最近浏览其他博客站点,看到很多朋友的网站上面侧边栏都有加上历史上的今天列表,能更好地展示一些没有更新的老文章,又可以提升页面的权重,那么我们应该如何在文章页面下添加一个“历史上的今天”功能获取老文章列表予以展示呢?下面就来教大家制作方法。

该功能代码取至柳城大佬的 wp-today 插件,具体实现方法将以下代码添加到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> <a href='".$h_permalink."' title='".$h_post_title."' target='_blank' rel="noopener">$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(); ?>

样式文件的话没有调整,大家根据自己喜好自行调整一下吧。

赞(32) 加关注
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:如何为WordPress文章添加历史上的今天列表
文章链接:https://www.xinfangs.com/909.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

评论 抢沙发

评论前必须登录!

立即登录   注册

请一秒记住我们的网址:www.xinfangs.com !

去投稿去留言

扫码关注公众号

非常感谢,让我们一起创建更加美好的网络世界!

关注公众号

加微信

登录

找回密码

注册