首页显示随机文章,能够保持首页经常处于更新状态,这样的好处不言自明。耕堂用的这个方法参考一款wordpress插件(结尾有介绍),其实有很多相关文章插件也提供类似的功能,不过下面的方法不需要安装插件。
1.打开当前主题的function.php文件,添加如下代码:
function random_posts ($limit = , $length = , $before = ”, $after = ”, $show_pass_post = false, $show_excerpt_in_title = true) {
global $wpdb, $tableposts;$sql = “SELECT ID, post_title, post_date, post_content FROM $tableposts WHERE post_status = ‘publish’ “;
if(!$show_pass_post) $sql .= “AND post_password =” “;
$sql .= “ORDER BY RAND() LIMIT $limit”;
$posts = $wpdb->get_results($sql);
$output = ”;
foreach ($posts as $post) {
$post_title = stripslashes($post->post_title);
$post_date = mysql2date(‘j.m.Y’, $post->post_date);
$permalink = get_permalink($post->ID);
$post_content = strip_tags($post->post_content);
$post_content = stripslashes($post_content);
$post_strip = substr($post_content,0,$length);
$post_strip = str_replace(‘”‘, ”, $post_strip);
$output .= $before . ‘<a href=”‘ . $permalink . ‘” rel=”bookmark” title=”‘;
if($show_excerpt_in_title) {
$output .= $post_strip . ‘… ‘;
} else {
$output .= ‘Permanent Link: ‘ . str_replace(‘”‘, ”, $post_title) . ‘… ‘;
}
$output .= $post_date . ‘”>’ . $post_title . ‘</a>’;
if(!$show_excerpt_in_title) {
$output .= ‘: ‘ . $post_strip . ‘… ‘;}
$output .= $after;
}
echo $output;
}?>
可以自定义的参数:
在第一行各参数,其含义为:
limit:显示文章数,自行输入数字;
length:显示文章摘要长度,自行输入数字;
before:每个文章标题前显示的内容,可以是文字或如<li>的html标签;
after:与before同理,标题后的内容,如果是html标签要与before的值对应;
show_pass_post表示是否显示被保护文章,值为true或false;
show_excerpt_in_title表示文章摘要是显示在链接的title参数里,还是显示在页面上,值为true或false;
其他代码不需改动。
2.在需要显示的模板文件适当地方添加代码:
php的if条件语句很有用,研究wordpress时经常用到,要学会并善于运用。
完成上面两步,就可以了,耕堂测试通过,有兴趣的朋友测试时有任何问题可以留言,保证回复解答,代码可以保证无误。首页随机的好处,每刷新一次页面,随机文章不同,这样首页就相当于经常更新,可以吸引蜘蛛来,首页快照一般也会是最近日期的。
p.s.鸣谢:插件Random Posts for Chinese,作者:Mulberry —http://yanfeng.org
另外,这款插件在下载页可以找到random-posts包(包含使用说明)。
右上方更多相关内容/站内搜索-关键词请用空格隔开
博主我试着所教的这样做,好像不行哦,能否与我讲解一下,是不是哪个地方我弄错了,谢谢~!