Typecho获取随机文章函数

时间:2020-08-01   阅读:350
function getRandomPosts($random=5){
    $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);
if($result){
    foreach($result as $val){
        $obj = Typecho_Widget::widget('Widget_Abstract_Contents');
        $val = $obj->push($val);
        $post_title = htmlspecialchars($val['title']);
        $permalink = $val['permalink'];
        echo '<a href="'.$permalink.'" title="'.$post_title.'"><h5 class="card-title">'.$post_title.'</h5></a>';
    }
}
}


需要使用时在模板中调用<?php getRandomPosts(10);?>即可,这个随机文章函数的好处就是不光兼容mysql还兼容sqlite数据库。

完整使用方法

  • 1.将上面完整的随机文章代码丢进主题文件夹的function.php里面,保存;

  • 2.在需要添加随机文章的地方加上代码:<?php getRandomPosts(10);?>,保存;

  • 3.刷新页面,搞定!

文章转自:http://www.7tec.cn/246.html

上一篇:Typecho评论回复按钮文字自定义

下一篇:Typecho自定义个人设置页面

网友评论