Typecho 调取随机文章

第1步:

在function中加入如下代码:

function theme_random_posts($limit = 10){

    $defaults = array(
        'number' => $limit,
        'before' => '<ul class="list">',
        'after' => '</ul>',
        'xformat' => '<li><a href="{permalink}" title="{title}">{title}</a></li>'
    );
    $db = Typecho_Db::get();
     
    $sql = $db->select()->from('table.contents')
    ->where('status = ?','publish')
    ->where('type = ?', 'post')
    ->where('created <= unix_timestamp(now())', 'post') //添加这一句避免未达到时间的文章提前曝光
    ->limit($defaults['number'])
    ->order('RAND()');
     
    $result = $db->fetchAll($sql);
    echo $defaults['before'];
    foreach($result as $val){
    $val = Typecho_Widget::widget('Widget_Abstract_Contents')->filter($val);
    echo str_replace(array('{permalink}', '{title}'),array($val['permalink'], $val['title']), $defaults['xformat']);
    }
    echo $defaults['after'];
}

第2步:

在要显示随机文章的地方添加以下调用代码

<?php theme_random_posts('10');?>

参考资料

https://blog.frytea.com/archives/292/
https://cloud.tencent.com/developer/article/1858286
https://www.dpaoz.com/9
https://blog.zwying.com/archives/40.html

版权声明:转载或引用请注明出处

点赞 0

添加新评论

验证码: