昨天介绍的《如何让WordPress侧边栏文本小工具运行php代码》这篇文章是本文的基础,只有WordPress侧边栏文章小工具具备了运行PHP代码的能力,才能更容易地实现侧边栏上显示历史上的今天这个功能。
其实历史上的今天的两个版本,主要是针对“今天”而言,因为这个“今天”有两重意思:
一是针对某篇文章的发布日期而言,这个版本只适用于正文侧边栏。
二是针对现实的时间(其实是服务器主机时间)而言,这个版本既适用于正文侧边栏,也适用于整站侧边栏。
一、侧边栏实现针对某篇文章的发布日期而言的历史上今天功能
第一步:将以下代码添加到我们主题的functions.php 文件中。
- //历史上的今天,代码来自柳城博主的WP-Today插件
- function wp_today(){
- global $wpdb;
- $post_year = get_the_time(‘Y’);
- $post_month = get_the_time(‘m’);
- $post_day = get_the_time(‘j’);
- $sql = “select ID, year(post_date_gmt) as h_year, post_title,
- comment_count FROM
- $wpdb->posts WHERE post_password = ” AND
- post_type = ‘post’ AND post_status = ‘publish’
- AND year(post_date_gmt)!=’$post_year’ AND
- month(post_date_gmt)=’$post_month’ AND day(post_date_gmt)=’$post_day’
- order by post_date_gmt DESC limit 5″;
- $histtory_post = $wpdb->get_results($sql);
- if( $histtory_post ){
- foreach( $histtory_post as $post ){
- $h_year = $post->h_year;
- $h_post_title = $post->post_title;
- $h_permalink = get_permalink( $post->ID );
- $h_comments = $post->comment_count;
- $h_post .=
- “<li><strong>$h_year:</strong> <a href='”.$h_permalink.“‘
- title='”.$h_post_title.“‘ target=’_blank’>$h_post_title($h_comments)
- </a></li>”;
- }
- }
- if ( $h_post ){
- $result = “<ul>”.$h_post.“</ul>”;
- }
- return $result;
- }
第二步:添加一个文本小工具到正文侧边栏中,然后在该文本小工具的标题中输入:历史上的今天,在内容中输入以下代码并保存:
- <?php echo wp_today(); ?>
具体如下图所示:
保存成功后,即可在我们正文的侧边栏看到历史上的今天相关的文章。这个版本只可以添加到正文的侧边栏中。
Unite主题侧边栏显示历史上的今天效果图如下:
二、侧边栏实现针对现实的时间而言的历史上今天功能
其实这个步骤跟“侧边栏实现针对某篇文章的发布日期而言的历史上今天功能”是一样的,代码也差不多,只需要将以下代码:
- $post_year = get_the_time(‘Y’);
- $post_month = get_the_time(‘m’);
- $post_day = get_the_time(‘j’);
改为:
- $post_year = date(‘Y’);
- $post_month = date(‘m’);
- $post_day = date(‘j’);
即可。这个版本是可以添加到整站的侧边栏中,没有任何限制。
温馨提示:
如果站点的文章量不多,不建议在侧边栏实现历史上的今天这个功能,因为如果没有符合的文章,侧边栏就只显示一个标题:历史上的今天,这样看起来有点不爽,不介意的除外。所以在此建议大家还是把历史上的今天这个功能放在文章后面比较实在,具体可见《WordPress网站纯代码添加历史上的今天功能》这篇文章。