我觉得我的博客的针对用户内容连续阅读的优化不到位,于是想添加这个功能,为typecho博客文章页脚添加"随机文章"和"猜你想看",参照了《逍遥隐士》的博客
在 /usr/themes/handsome/post.php
中加入如下代码(在110行左右):
<!--随机及相关文章-->
<?php $this->related(3)->to($relatedPosts); ?>
<?php if ($relatedPosts->have()): ?>
<!-- 相关文章 -->
<div class="list-group col-lg-6">
<span class="list-group-item tt-suiji-title">
猜你想看
</span>
<?php while ($relatedPosts->next()): ?>
<a class="list-group-item text-ellipsis" href="<?php $relatedPosts->permalink(); ?>" title="<?php $relatedPosts->title(); ?>"><?php $relatedPosts->title(); ?></a>
<?php endwhile; ?>
</div>
<!--随机文章-->
<div class="list-group col-lg-6">
<span class="list-group-item tt-suiji-title">
随机文章
</span>
<?php getRandomPosts(3);?>
</div>
<?php else: ?>
<!--随机文章-->
<div class="list-group">
<span class="list-group-item tt-suiji-title">
随机文章
</span>
<?php getRandomPosts(3);?>
</div>
<?php endif; ?>
<!--随机及相关文章 End-->
在 /usr/themes/handsome/functions_mine.php
的末尾 添加如下代码(在1087行左右):
/**
* 随机文章,在需要添加随机文章的地方加上代码:<?php getRandomPosts(5);?>
* 数字5为要调用的文章数量。
*/
function getRandomPosts($random)
{
$modified = $random->modified;
$db = Typecho_Db::get();
$adapterName = $db->getAdapterName();//兼容非MySQL数据库
if ($adapterName == 'pgsql' || $adapterName == 'Pdo_Pgsql' || $adapterName == 'Pdo_SQLite' || $adapterName == 'SQLite') {
$order_by = 'RANDOM()';
} else {
$order_by = 'RAND()';
}
$sql = $db->select()->from('table.contents')
->where('status = ?', 'publish')
->where('table.contents.created <= ?', time())
->where('type = ?', 'post')
->limit($random)
->order($order_by);
$result = $db->fetchAll($sql);
foreach ($result as $val) {
$val = Typecho_Widget::widget('Widget_Abstract_Contents')->push($val);
echo '<a class="list-group-item text-ellipsis" href="' . $val['permalink'] . '" title="' . $val['title'] . '"> ' . $val['title'] . ' </a>';
}
}