Typecho获取随机文章函数

typecho教程 2020-08-25

  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

  ->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 ‘

‘.$post_title.’

‘;

  }

  }

  }

  需要使用时在模板中调用即可,这个随机文章函数的好处就是不光兼容还兼容数据库。

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

评论 (0)
    Top