前几天博主发问了,“如何让Typecho搭建的网站首页文章随机显示?各位大佬支支招!”,在各大大佬@LiuShen@无名博客@临时访问@目的地-Destination@Lopwon@的指点下结合AI最终实现了文章随机显示办法。

修改文件地址:主题文件/components/post-list.php

主要修改内容:

👉 改动要点:

  1. 增加 $posts = [] 数组:用来存放文章对象。
  2. while ($this->next()) { $posts[] = clone $this; } 收集文章:不直接输出,而是放进数组。
  3. 调用 shuffle($posts); :打乱数组顺序,实现随机化。
  4. foreach ($posts as $item) 遍历输出:把原来 $this 改成 $item,其它结构(标题、摘要、时间、作者等)保持不变。

    ### 原版

    原版
    <?php while ($this->next()): ?>
        ... 输出文章内容 ...
    <?php endwhile; ?>
    
    
    👉 意思是 按数据库查询结果的顺序(默认按时间倒序)逐篇输出文章。
    
    修改后
    <?php 
    $posts = [];
    
    // 先收集文章
    while ($this->next()) {
        $posts[] = clone $this;
    }
    
    // 打乱顺序
    shuffle($posts);
    
    // 再输出文章
    foreach ($posts as $item): ?>
        ... 输出文章内容 ...
    <?php endforeach; ?>

发表评论