先在模板的function.php中加入随机文章方法代码
function theme_random_posts(){
$defaults = array(
'number' => 5,
'before' => '<ul class="list">',
'after' => '</ul>',
'xformat' => '<li><a href="{permalink}" title="{title}">{title}</a></li>'
);
$db = Typecho_Db::get();
$sql = $db->select()->from('table.contents')
->where('status = ?','publish')
->where('type = ?', 'post')
->where('created <= unix_timestamp(now())', 'post') //添加这一句避免未达到时间的文章提前曝光
->limit($defaults['number'])
->order('RAND()');
$result = $db->fetchAll($sql);
echo $defaults['before'];
foreach($result as $val){
$val = Typecho_Widget::widget('Widget_Abstract_Contents')->filter($val);
echo str_replace(array('{permalink}', '{title}'),array($val['permalink'], $val['title']), $defaults['xformat']);
}
echo $defaults['after'];
}
然后再需要调用随机文章的地方插入此代码(如sidebar.php\post.php)
<?php theme_random_posts();?>
另外也可以自己修改输出效果
'xformat' => '<li><a href="{permalink}" title="{title}">{title}</a></li>'
改成
'xformat' => '<li><a href="{permalink}" title="{title}">{title}</a><p>{text}</p></li>'
然后将
echo str_replace(array('{permalink}', '{title}'),array($val['permalink'], $val['title']), $defaults['xformat']);
改成
echo str_replace(array('{permalink}', '{title}', '{text}'),array($val['permalink'], $val['title'], cutArticle($val['text'],100)), $defaults['xformat']);
另外在function.php中增加一段将正文转成摘要的代码
function cutArticle($data,$cut=0,$str="....")
{
$data=strip_tags($data);//去除html标记
$pattern = "/&[a-zA-Z]+;/";//去除特殊符号
$data=preg_replace($pattern,'',$data);
if(!is_numeric($cut))
return $data;
if($cut>0)
$data=mb_strimwidth($data,0,$cut,$str);
return $data;
}