您只想在 WordPress 帖子循环中显示子类别吗?
大多数 WordPress 主题都会显示帖子的所有类别,包括父类别和子类别。但是,如果您在帖子中添加大量类别,那么这可能会使您的网站看起来很混乱,并阻止读者找到有趣的内容。
在本文中,我们将向您展示如何轻松地在 WordPress 帖子循环中仅显示子类别。
创建 WordPress 博客时,您可以使用类别和标签来组织内容。
为了帮助读者更快地找到有趣的内容,您甚至可以创建子类别(或子类别)。
例如,如果您有一个旅游博客,那么您可以创建一个“目的地”类别,然后创建“欧洲”、“美国”和“澳大利亚”等子类别。
默认情况下,大多数 WordPress 主题显示帖子的所有父类别和子类别。
但是,如果您使用大量类别,那么您的博客页面可能会开始显得混乱和复杂。它还会让读者更难找到他们感兴趣的类别。
因此,您可能希望隐藏帖子的通用父类别并仅显示子类别。话虽这么说,让我们看看如何在 WordPress 后循环中仅显示子类别。
要隐藏帖子的父类别,您需要向 WordPress 网站添加代码。如果您以前没有这样做过,那么您可以查看我们的初学者指南,了解如何将网络片段粘贴到 WordPress 中。
首先,您需要在主题文件中找到负责显示类别的代码。它通常位于 WordPress 主题内的 single.php 文件中。
为了帮助您找到正确的模板文件,请参阅我们的 WordPress 模板层次结构备忘单。当您找到负责显示类别的代码后,可以将其替换为以下代码:
// Get the IDs of categories
$categories = get_the_category();
foreach( $categories as $category ) {
If ( $category->parent > 0 ) {
$child_cat_ID[] = $category->term_id;
//store child's parent category id to use later
$parent_cat_ID = $category->parent;
}
// find categories with no parent and no child
If ( $category->parent == 0 && $category->term_id !== $parent_cat_ID) {
$single_category[] = $category->term_id;
}
}
// Display part of the code
// if there are no child categories then go ahead and display all categories.
If ( empty($child_cat_ID)) {
echo get_the_category_list( ' , ', '' );
}
// If there are child categories then do this
else {
$child_cat_IDs = implode(', ', $child_cat_ID) ;
$single_category_id = implode(', ', $single_category);
// Combine child categories and categories with no children
$cats_to_include = $child_cat_IDs . ', ' . $single_category_id ;
// Display them
echo '<div class="post-categories">Filed under: ';
wp_list_categories( array(
'separator' => ' ',
'style' => '',
'include' => $cats_to_include
) );
echo '</div>';
}
此代码将仅排除父类别,因此它将继续显示没有子类别的任何独立类别。
完成后,保存更改,然后将文件上传回您的网络托管服务器。
现在,您需要访问具有一个或多个子类别的帖子。您会看到父类别已隐藏,并且 WordPress 现在仅显示子类别。
我们希望本文能帮助您了解如何在 WordPress 帖子中仅显示子类别。接下来,您可能想查看我们关于如何使用 WordPress 在线博客赚钱的指南,或者查看我们的专家精选的您应该使用的最佳 SEO 插件和工具。
如果您喜欢这篇文章,请订阅我们的 WordPress 视频教程 YouTube 频道。您还可以在 Twitter 和 Facebook 上找到我们。