大家可能在管理网站时慢慢失去了更新网站的动力,又或者我们的网站有许多优质的老文章、却无人问津,在这些情况下,我们就有需要为WordPress添加伪更新的功能,这个功能可以在特定时间于网站的首页内自动随机显示一篇随机文章,让你的旧文章也焕发出光芒!
教学
提示:本站首页的首篇及尾篇文章所使用的是全随机文章、也就是在没有缓存的情况下每次刷新都将会出现不同的文章,与本文所实现的效果不同!
1、首先,将下方代码添加到「布景函式库 (functions.php)」的最底部 ?> 之前,然后点击 更新档案
注意:如果你的首页文章概要不是通过模板 get_template_part 函数所获取、你需要将「index.php」中显示文章概要的代码替换下方 show_the_index 函数的代码!
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | /* 为你的WordPress添加伪更新功能开始(由AREFLY.COM制作) */ function show_the_index() { 	// 注意:如果你的首页文章概要不是通过模板(get_template_part函数)所获取、你需要将index.php中显示文章概要的代码替换下方的代码! 	get_template_part('entry', get_post_format()); } function home_page_stored_random_post($count = 24) { 	global $wpdb; 	$last = $wpdb->get_results("SELECT MAX(post_date) AS MAX_m FROM $wpdb->posts WHERE (post_type = 'post' ) AND (post_status = 'publish' )"); 	$laststamp = strtotime($last[0]->MAX_m); 	$hours = (time()+3600*8 - $laststamp)/3600; 	if($hours > $count) {	//如果当前时间距离最后一次更新文章的时间已经超过 $count 的数值,则执行伪更新 		if((time()+3600*8 - get_option("random_post_last_time"))/3600 > $count) { 			update_option("random_post_last_time", time()+3600*8); 			$rand_query = new WP_Query("showposts=1&orderby=rand"); 			if($rand_query->have_posts()){ 				while($rand_query->have_posts()){ 					$rand_query->the_post(); 					global $id; 					update_option("random_post_postid", $id); 					show_the_index();	//调用主题式样显示该文章 				} 			} 		} else { 			$rndpostid = get_option("random_post_postid"); 			$rand_query = new WP_Query("p=" .$rndpostid); 			if($rand_query->have_posts()){ 				while($rand_query->have_posts()){ 					$rand_query->the_post(); 					show_the_index();	//调用主题式样显示该文章 				} 			} 		} 	} } function home_page_random_post() {	//【该函数即上文所提本站使用之功能】在每次刷新后显示不同的随机文章 	global $wpdb; 	$last = $wpdb->get_results("SELECT MAX(post_date) AS MAX_m FROM $wpdb->posts WHERE (post_type = 'post' ) AND (post_status = 'publish' )"); 	$rand_query = new WP_Query("showposts=1&orderby=rand"); 	if($rand_query->have_posts()){ 		while($rand_query->have_posts()){ 			$rand_query->the_post(); 			global $id; 			show_the_index(); 		} 	} } /* 为你的WordPress添加伪更新功能结束(由AREFLY.COM制作) */ | 
2、将下列代码添加(高亮部分)到「index.php」中的 <?php if (have_posts()) : ?> 之前以加载随机文章:(可以将 12 改为任意小时数)
| 1 2 3 4 5 6 7 | <?php if(function_exists('home_page_stored_random_post')) home_page_stored_random_post(12); ?> <?php if (have_posts()) : ?> 	<?php while ( have_posts() ) : the_post(); ?> 		//该段代码即前文所述之【文章概要代码】! 		<?php get_template_part('entry', get_post_format()); ?> 	<?php endwhile; ?> <?php endif; ?> | 
3、现在刷新你的首页看看,如果你的上一篇文章更新时间少于 $count 内的小时数,应该你的网站就会自动调用一篇文章来显示啦!  
 
参考
WordPress技巧:令你的站点保持更新的方法 — 伪更新 — 随机更新
历史上的今天
2013年:澳门之旅(7条评论)
