精彩资源分享
我的公开个人笔记

纯代码WordPress文章添加历史上的今天功能

当网站历史越来越悠久,想要体现网站的历史,可以给网站文章添加历史上的今天,在发表文章以后,N年同天时间发表的文章也会显示出来,不过对于网站年龄只有一两年的时间其实没啥用的,没有文章显示出来,不过也记录一下。弄后效果如下图!

纯代码无需插件,只需把下面代码添加到主题的function.php即可。

function wp_history_post_base($post_year, $post_month, $post_day){
	global $wpdb;
	$limit = 30;
	$order = "latest";
	if($order == "latest"){ $order = "DESC";} else { $order = '';}
	$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 $order limit $limit";
	$histtory_post = $wpdb->get_results($sql);
	return $histtory_post;
}
 
function wp_history_post_single(){
	$wp_history_post_content_list = '<p>%YEAR%年:<a href="%LINK%" title="%TITLE%" rel="external nofollow">%TITLE%(%COMMENTS_NUM%条评论)</a></p>';
	$wp_history_post_content_title = '<h3>历史上的今天</h3>';
	$histtory_post = wp_history_post_base(get_the_time('Y'), get_the_time('m'), get_the_time('j'));
	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 .= $wp_history_post_content_list;
	$h_post = str_replace("%YEAR%", $h_year, $h_post);
	$h_post = str_replace("%LINK%", $h_permalink, $h_post);
	$h_post = str_replace("%TITLE%", $h_post_title, $h_post);
	$h_post = str_replace("%COMMENTS_NUM%", $h_comments, $h_post);
	}
	}
	if($h_post){
	$result = $wp_history_post_content_title.$h_post;
	}
	return $result;
	wp_reset_query();
}
 
function wp_history_post_content($content){
	global $wpdb;
	if(is_single()){
	$content .= wp_history_post_single();
	}
	return $content;
}
add_action('the_content', 'wp_history_post_content');
历史上的今天
十二月
6
    哇哦~~~,历史上的今天没发表过文章哦
赞(0) 打赏
未经允许不得转载:安小客博客 » 纯代码WordPress文章添加历史上的今天功能

评论 抢沙发

8 + 8 =
  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏