wordpress - Wordpress 将父类别显示为标题,下方有子项
问题描述
我有一个祖父母类别,其中包括这样的孩子和孙子:
- 祖父母猫
- 儿童猫 01
- 孙子猫 01
- 孙子猫 02
- 孙子猫 03
- 儿童猫 02
- 孙子猫 01
- 孙子猫 02
- 孙子猫 03
- 儿童猫 01
我想在主要的祖父母类别页面上循环浏览这些内容,并显示每个子标题,下面有孙子链接。
到目前为止,我有这个显示所有子孙,但没有区分两者......
<?php
$this_category = get_category($cat);
$args = (array (
'orderby'=> 'id',
'depth' => '1',
'show_count' => '0',
'child_of' => $this_category->cat_ID,
'echo' => '0'
));
$categories = get_categories( $args );
foreach ( $categories as $category ) {
echo $category->name
} ?>
如果有孩子,我需要一个规则...
解决方案
通过检查类别是否有父类别来识别这相对简单
<?php
$this_category = get_category($cat);
$args = (array (
'orderby'=> 'id',
'depth' => '1',
'show_count' => '0',
'child_of' => $this_category->cat_ID,
'echo' => '0'
));
$categories = get_categories( $args );
foreach ( $categories as $category ) {
if (!$category->parent) {
echo 'Has no parent';
}
echo $category->name;
} ?>
或者递归方法,具体取决于您的需要
<?php
$this_category = get_category($cat);
function category_tree(int $categoryId = 0) {
$categories = get_categories([
'parent' => $categoryId,
'echo' => 0,
'orderby' => 'id',
'show_count' => 0
]);
if ($categories) {
foreach ($categories as $category) {
echo '<ul>';
echo '<li>';
echo $category->name;
category_tree($category->term_id);
}
}
echo '</li></ul>';
}
category_tree($this_category->cat_ID);
推荐阅读
- javascript - 如何向使用 ES6 的模板文字创建的元素添加函数/事件侦听器?
- react-native - 无法在 Modal 中设置 FlatList 高度
- javascript - facebook 自动使用登录 facebook 应用程序的用户进行身份验证
- c# - OdbcDataAdapter 表名称 - 在 C 中
- kubernetes - 无法通过主节点访问 pod 网络
- bash - 用于创建 mongo 数据库文档的 cURL 脚本
- c++ - 为什么 osgEarth 不使用 Qt 构建?
- python - Python烧瓶应用程序事件处理程序
- node.js - 尝试“npm install node-sass --save dev”时出错
- r - 求和并将其放在 R 中的其他位置