腾讯云服务器优惠活动华纳云香港服务器

WordPress网站纯代码添加历史上的今天功能

WordPress主题推荐

前几天在boke112导航上推荐了柳城博主的WordPress插件:历史上的今天wp-today,有很多网友说这个插件很实用,希望折腾成纯代码版分享。其实这个都是WordPress插件多了会拖慢网页打开速度的心理在作怪,不过本站也想添加这个功能,所以就顺手折腾成纯代码版分享给大家。

WordPress网站纯代码添加历史上的今天功能-第1张-boke112百科(boke112.com)

纯代码实现历史上的今天这个功能,还是非常简单的,只需要把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>&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样式大家自行调整即可。

3、效果图

WordPress网站纯代码添加历史上的今天功能-第2张-boke112百科(boke112.com)

4、具体运行效果:传送门

本文地址:https://boke112.com/post/2707.html

赞 (0) 打赏
版权声明:本文为投稿文章,感谢 懿古今 的投稿,版权归原作者所有!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu