Typecho实现随机进入一篇文章

Typecho实现随机进入一篇文章

2023年12月16日 作者头像 作者头像 泽泽社长 编辑

评论

0 Count

Typecho随机文章的函数如下:

function randomPost($type='echo') {
    $db = Typecho_Db::get();
    $result = $db->fetchRow($db->select()->from('table.contents')->where('type=?', 'post')->where('status=?', 'publish')->limit(1)->order('RAND()'));
    if($result) {
        $f=Helper::widgetById('Contents',$result['cid']);
        $permalink = $f->permalink;
        if($type=="return"){return $permalink;}else{echo $permalink;}
    } else {
        if($type=="return"){return false;}else{echo "没有文章可随机";}
    }
}

使用

直接调用randomPost()即可输出随机出来的文章地址,使用randomPost("return")可返回随机到的文章地址。

不过为了方便使用,我们最好固定出来个api来进行调用,如下:

function themeInit($archive)
{
if($archive->request->isGet() && $archive->request->get('random')){
    header('Location: '.randomPost('return'));exit;
}
}

之后我们访问你的域名?random=true即可随机进入文章。