WordPress详情页底部调取历史上的今天

2021年6月4日17:02:58 发表评论 9
广告也精彩

如果你不想折腾,可以直接使用插件也解决问题。wordpress历史上的今天插件:WP-Today

WordPress详情页底部调取历史上的今天

当然如果你喜欢折腾,可以手动添加代码,本功能是使用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(!emptyempty($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(); ?>

当然样式需要你自己来整了。可根据html结构进行定制,已经添加了相应class。
 

 

 

 

 

 

 



微信扫描下方的二维码阅读本文

ts小陈

发表评论(请规范评论)--评论需审核

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

已登录用户不需要填写以下内容