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

版权属于:泽泽社长
本文链接:https://blog.zezeshe.com/archives/typecho-getRandomPosts-functions.html
本站未注明转载的文章均为原创,并采用 CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!