WordPress加入历史上今天发表的文章功能

本功能是列出站内历史上的今天发布的文章,而不是之前历史上发生的大事。所以想正常使用本功能,首先需要的是你站点运行超过1年了,如果还不到一年,那自然不会有什么历史上的今天了。

 

代码

首先在主题的functions.php加入以下代码:

function today_in_history() {
 
	$title = "历史上的今天"; // 标题
	$limit = 5; // 列表显示的数量,默认5条数据
 
	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 $limit";
	$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>$h_year:&nbsp;&nbsp;<a href='".$h_permalink."' title='查看: ".$h_post_title."'>$h_post_title <span>($h_comments 评)</span></a></li>";
		}
	}
 
	if ( $h_post ){
		$result = "<section class='history-in-today'><p><strong>".$title."</strong></p><div><ul>".$h_post."</ul></div></section>";
	} else {
		$result = "<section class='history-in-today'><p><strong>".$title."</strong></p><div>很遗憾~,历史上的今天未发表过文章</div></section>";
	}
 
	return $result;
}

在需要展示的地方(例如文章底部),加入引用代码:

<?php echo today_in_history(); ?>

然后就会看到效果了,如果曾经未发布过文章,会提示:“很遗憾~,历史上的今天未发表过文章”,反之则显示文章列表,样式自己改改就好了。

温馨提示: 本文最后更新于2019-07-11,至今已有1751天,某些文章具有时效性,若有错误或已失效,请在下方留言
© 版权声明
THE END
喜欢就支持一下吧❀
点赞1投币 分享
评论 抢沙发

    请登录后查看评论内容