给WordPress添加伪更新功能 在首页随机显示文章

给WordPress添加伪更新功能 在首页随机显示文章  第1张

虽然博客是自己的地盘,但长时间不更新的话,从博客得到的负罪感要多于快乐。而更新是个伤脑筋的工程,技术的神奇之处就在于可以让懒惰变得简单。

1、将下方代码添加到“模板函数 (functions.php)”的最底部 ?> 之前。

注意:如果你的首页文章概要不是通过模板 get_template_part 函数所获取丶你需要将“index.php”中显示文章概要的代码替换下方 show_the_index函数的代码!

/* 为你的WordPress添加伪更新功能开始 */
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添加伪更新功能结束 *

2、将下列代码添加(高亮部分)到“index.php”中的 <?php if (have_posts()) : ?> 之前以加载随机文章:(可以将 12 改为任意小时数)

<?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; ?>

现在刷新你的首页看看,如果你的上一篇文章更新时间少於 $count 内的小时数,你的网站就会自动调用一篇文章来显示啦!

本文摘自:从良未遂
原文标题:为WordPress添加“伪更新”功能丶并在首页显示随机文章
原文链接:http://www.ithmz.com/pseudo-update.html

版权声明:本站部分文章为网络转载,文章结尾已注明出处,如侵犯您的权益请联系我们删除。

联系我们:turbochao@126.com

范超博客emlog博客主题模板分享