插件窝 干货文章 Typecho博客首页:如何隐藏多个指定分类的文章?

Typecho博客首页:如何隐藏多个指定分类的文章?

文章 分类 php index 977    来源:    2025-03-13

在Typecho博客中,如果你想在首页隐藏多个指定分类的文章,可以通过修改主题模板文件来实现。以下是具体的步骤:

方法一:修改 index.php 文件

  1. 找到主题的 index.php 文件: 通常位于 usr/themes/你的主题名称/index.php

  2. 修改 index.php 文件: 在 index.php 文件中找到文章循环的部分,通常是 $this->widget('Widget_Archive@index', 'type=index')->to($posts); 或类似的代码。

  3. 添加分类过滤: 在循环之前,添加一个条件来排除指定的分类。假设你想隐藏分类ID为 12 的文章,可以这样修改:

    <?php
    $this->widget('Widget_Archive@index', 'type=index')->to($posts);
    while ($posts->next()):
       // 获取当前文章的分类
       $categories = $posts->categories;
       $hide = false;
       foreach ($categories as $category) {
           // 如果分类ID为1或2,则隐藏
           if (in_array($category['mid'], [1, 2])) {
               $hide = true;
               break;
           }
       }
       if ($hide) continue; // 跳过隐藏的文章
    ?>
    <!-- 文章内容输出部分 -->
    <h2><?php $posts->title(); ?></h2>
    <div><?php $posts->content(); ?></div>
    <?php endwhile; ?>
    

    这段代码会在输出文章之前检查文章的分类,如果分类ID为 12,则跳过该文章。

方法二:使用插件

如果你不想手动修改代码,可以使用一些插件来实现这个功能。例如:

  • TePass:这是一个Typecho插件,可以帮助你隐藏指定分类的文章。
  • Sticky:这个插件可以让你设置某些文章为置顶或隐藏。

方法三:使用自定义查询

你也可以通过自定义查询来排除指定分类的文章。例如:

<?php
$db = Typecho_Db::get();
$select = $db->select()->from('table.contents')
    ->where('table.contents.type = ?', 'post')
    ->where('table.contents.status = ?', 'publish')
    ->where('table.contents.created < ?', Typecho_Date::gmtTime())
    ->where('table.relationships.mid NOT IN (1, 2)') // 排除分类ID为1和2的文章
    ->join('table.relationships', 'table.contents.cid = table.relationships.cid')
    ->order('table.contents.created', Typecho_Db::SORT_DESC);

$posts = $db->fetchAll($select);
foreach ($posts as $post) {
    $post = Typecho_Widget::widget('Widget_Abstract_Contents')->filter($post);
    ?>
    <h2><?php echo $post['title']; ?></h2>
    <div><?php echo $post['content']; ?></div>
    <?php
}
?>

这种方法直接在数据库查询时排除指定分类的文章。

总结

  • 方法一:通过修改 index.php 文件,手动添加分类过滤条件。
  • 方法二:使用插件来隐藏指定分类的文章。
  • 方法三:通过自定义查询在数据库层面排除指定分类的文章。

根据你的需求和技术水平,选择合适的方法来实现隐藏指定分类文章的功能。