前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >为typecho博客文章页脚添加"随机文章"和"猜你想看"

为typecho博客文章页脚添加"随机文章"和"猜你想看"

作者头像
小屁的博客
发布2022-05-13 19:50:25
发布2022-05-13 19:50:25
25600
代码可运行
举报
文章被收录于专栏:小屁折腾日记小屁折腾日记
运行总次数:0
代码可运行

前言

我觉得我的博客的针对用户内容连续阅读的优化不到位,于是想添加这个功能,为typecho博客文章页脚添加"随机文章"和"猜你想看",参照了《逍遥隐士》的博客

开始

/usr/themes/handsome/post.php 中加入如下代码(在110行左右):

代码语言:javascript
代码运行次数:0
运行
复制
<!--随机及相关文章-->
<?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行左右):

代码语言:javascript
代码运行次数:0
运行
复制
    /**
     * 随机文章,在需要添加随机文章的地方加上代码:<?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>';
        }
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021 年 09 月,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 开始
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档