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

admin wordpress评论692字数 1189阅读模式
摘要

本功能是展示站内历史上的今天发布的文章,而不是之前历史上发生的大事。所以想正常使用本功能,首先需要的是你站点运行超过1年了,如果还不到一年,那自然不会有什么历史上的今天了。
今天我就给大家带来如何无需插件使用代码来实现历史上的今天这个功能,本功能是使用wordpress自带的date_query来实现。

实现方法
下面的代码加入到functions.php中

  1. function fa_today_in_histroy(){  
  2.     $today = getdate();  
  3.     $args = array(  
  4.         'date_query' => array(  
  5.             array(  
  6.                 'year'      => $today['year'],  
  7.                 'compare'   => '!=',  
  8.             ),  
  9.             array(  
  10.                 'month' => $today['mon'],  
  11.                 'day'   => $today['mday'],  
  12.             ),  
  13.         ),  
  14.     );  
  15.     $postlist = get_posts($args);  
  16.     $html = '<h3 class="tih-title">历史上的今天</h3><ul class="tih-title-list">';  
  17.     if(!empty($postlist)){  
  18.         foreach ($postlist as $key => $post) {  
  19.             $html .= '<li class="tih-title-item"><a href="' . get_permalink($post->ID) . '" title="' . $post->post_title . '">' . $post->post_title . '</a></li>';  
  20.         }  
  21.         $html .= '</ul>';  
  22.         return $html;  
  23.     }  
  24. }  

注意,在这个循环中是不能直接调用各种wp文章函数的,如需使用wp文章函数,则需要使用setup_postdata()和wp_reset_postdata()
调用方法
如果是添加到文章末尾,可直接使用如下钩子,直接添加到functions.php中即可

  1. function add_today_in_histroy($content){  
  2.     global $post;  
  3.     return $content . today_in_histroy();  
  4. }  
  5. add_filter('the_content','add_today_in_histroy');  

如果是自定义位置,则使用

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

更多相关文章

如何给wordpress栏目链接和标签链接末尾加上正斜杠 /?

版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
admin
  • 本文由 发表于 2021年9月25日 11:45:04
  • 转载请务必保留本文链接:https://www.58pxe.com/7655.html
匿名

发表评论

匿名网友 填写信息

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