在使用Typecho博客系统时,通过在文末添加相关文章推荐、热评文章推荐、最新文章推荐,可以增加网站内链,有利于 SEO 优化。我使用的是handsome主题,其他主题操作方法类似。以下是在 Handsome 主题中实现这三种文章推荐的具体步骤:

一、相关文章推荐

  • 实现原理 :相关文章推荐通常是基于当前文章的标签,找到具有相同标签的其他文章进行推荐。
  • 代码修改 :在主题文件夹下的 post.php文件中合适位置添加以下代码:
<div class="tab-content clear">
    <h4 class="widget-title m-t-none text-md"><?php _me("※相关文章推荐※ ") ?></h4>
    <div id="relatedPosts">
        <ul class="list-group-item  nav nav-list">
            <?php $this->related(6)->to($relatedPosts); ?>
            <?php if ($relatedPosts->have()): ?>
                <?php while ($relatedPosts->next()): ?>
                <li>
                    <a href="<?php $relatedPosts->permalink(); ?>" title="<?php $relatedPosts->title(); ?>"><?php $relatedPosts->title(); ?></a>
                </li>
                <?php endwhile; ?>
            <?php else : ?>
            <li>暂无相关推荐</li>
            <?php endif; ?>
        </ul>
    </div>
</div>

二、热评文章推荐

  • 实现原理 :热评文章推荐是根据文章的评论数进行排序,选出评论数较多的文章进行推荐。
  • 函数定义 :首先,在 function.php的底部增加一个函数:
function getHotComments($limit = 5) {
    $db = Typecho_Db::get();
    $result = $db->fetchAll($db->select()->from('table.contents')
        ->where('status = ?', 'publish')
        ->where('type = ?', 'post')
        ->limit($limit)
        ->order('commentsNum', Typecho_Db::SORT_DESC)
    );
    if ($result) {
        foreach ($result as $val) {
            $val = Typecho_Widget::widget('Widget_Abstract_Contents')->push($val);
            $post_title = htmlspecialchars($val['title']);
            $permalink = $val['permalink'];
            echo '<li><a href="' . $permalink . '" title="' . $post_title . '" target="_blank">' . $post_title . '</a></li>';
        }
    }
}
  • 调用函数 :然后在 post.php文件里增加以下代码调用该函数:
<div class="tab-content clear">
    <h4 class="widget-title m-t-none text-md"><?php _me("※热评文章推荐※") ?></h4>
    <div id="relatedPosts">
        <ul class="list-group-item  nav nav-list">
            <li><?php getHotComments('5'); ?></li>
        </ul>
    </div>
</div>

三、最新文章推荐

  • 实现原理 :最新文章推荐是根据文章的发布时间进行排序,选出最新的文章进行推荐。
  • 代码修改 :在 post.php文件中合适位置添加以下代码:
<div class="tab-content clear">
    <h4 class="widget-title m-t-none text-md"><?php _me("※最新文章推荐※") ?></h4>
    <div id="relatedPosts">
        <ul class="list-group-item  nav nav-list">
            <?php
            $recent = $this->widget('Widget_Contents_Post_Recent', 'pageSize=6');
            if ($recent->have()):
                while ($recent->next()):
            ?>
            <li><a href="<?php $recent->permalink(); ?>"><?php $recent->title(); ?></a></li>
            <?php endwhile; endif; ?>
        </ul>
    </div>
</div>

四、注意事项

  • 在进行代码修改之前,建议先备份相关的主题文件,以免修改出错后难以恢复。
  • 可以根据实际需求调整推荐文章的数量,如将代码中的数字 65修改为其他数字。
  • 如果对样式不满意,可以通过自定义 CSS 来调整推荐文章的显示效果,使其更好地融入网站的整体风格。

参考:

Handsome主题文末添加相关文章推荐、热评文章推荐、最新文章推荐(Typecho)

最后修改:2025 年 07 月 03 日
如果觉得我的文章对你有用,请随意赞赏