Typecho 纯代码实现随机进入一篇文章

今天来讲讲 Typecho 随机文章 的实现 功能代码 ,在主题文件 function.php文件添加以下代码:

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"){returnfalse;}else{echo"没有文章可随机";}
    }
}

代码使用

前台直接调用<?php randomPost(); ?>即可输出随机出来的文章地址,使用<?php randomPost("return"); ?>可返回随机到的文章地址。

不过为了方便使用,我们最好固定出来个api来进行调用,在主题文件 function.php文件添加以下代码:

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

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

请登录后发表评论

    没有回复内容