导航菜单

Typecho 获取上一篇下一篇的获取方法是

$this->theNext();
$this->thePrev();

这个返回只有部分信息不方便获取额外信息。
其实翻看代码直接抽取查询代码就可以自己扩展了

function getNextPost($archive)
{
    $db = Typecho_Db::get();
    $post = $db->fetchRow($db->select()->from('table.contents')->where('table.contents.created > ? AND table.contents.created < ?', $archive->created, Helper::options()->time)
        ->where('table.contents.status = ?', 'publish')
        ->where('table.contents.type = ?', $archive->type)
        ->where("table.contents.password IS NULL OR table.contents.password = ''")
        ->order('table.contents.created', Typecho_Db::SORT_ASC)
        ->limit(1));

    return $post;
}
function getPrevPost($archive)
{
    $db = Typecho_Db::get();
    $post = $db->fetchRow($db->select()->from('table.contents')->where('table.contents.created < ?', $archive->created)
        ->where('table.contents.status = ?', 'publish')
        ->where('table.contents.type = ?', $archive->type)
        ->where("table.contents.password IS NULL OR table.contents.password = ''")
        ->order('table.contents.created', Typecho_Db::SORT_DESC)
        ->limit(1));
    return $post;
}

使用很简单,比如我想获取缩略图

$post = getPrevPost($this);
$thumbnail = getThumbnail($post['conent'])

$post是一个数组,getThumbnail()是我写的用于获取缩略图的方法。
如果想获取文章创建时间

date('Y-m-d H:i:s', $post['created'])

如果想把获取的的查询结果转成 $widget 对象的话,通过$widget->content来获取文章内容,可以这么操作(这个方法只需要一次数据库查询)

价格: 3.50 元
VIP会员价格:2.80元终身会员价格:2.00元
温馨提示:登录付款后可永久阅读隐藏内容。 付费可读

然后就可以通过

<?php $nextPost = getNextPost($this); ?>
<a href="<?php $nextPost->permalink() ?>">
   <span class="item"><?php $nextPost->title(); ?></span>
   <span class="item"><img src="<?php echo getThumbnail($nextPost); ?>"/></span>
   <span class="item"><?php $this->created(); ?></span>
   <span class="item"><?php $this->date(); ?></span>
</a>

来获取下一篇文章对应的信息了

2021.02.25更新

判断下一篇不存在不输出

<?php $nextPost = getNextPost($this); ?>
<?php if ($nextPost->have()) : ?>
<a href="<?php $nextPost->permalink() ?>">
   <span class="item"><?php $nextPost->title(); ?></span>
   <span class="item"><img src="<?php echo getThumbnail($nextPost); ?>"/></span>
   <span class="item"><?php $this->created(); ?></span>
   <span class="item"><?php $this->date(); ?></span>
</a>
<?php endif; ?>

已有 8 条评论

  1. chenmo
    湖南省

    现在最新的5.0以上版本也是这样子改吗?

  2. chenmo
    湖南省

    $post = getPrevPost($this);
    $thumbnail = getThumbnail($post['conent'])

    这是怎么用的?

    1. Ryan
      未知地区

      在文章页面直接调用啊

  3. chenmo
    湖南省

    date('Y-m-d H:i:s', $post['created']) 获取的时间是1611234288 这样的数字
    好像下一篇文章到头的时候,它还是会出随机图,但标题是没了

  4. chenmo
    湖南省

    1.2版本中好像报错了,博主能修复一下吗?

  5. chenmo
    湖南省

    判断下一篇不存在不输出 这个好像失效了 会错误输出上一篇

  6. chenmo
    湖南省

    我的打开最后一篇文章 的话 下一篇会显示和上一篇一样的文章内容。我加了if ($nextPost->have())