如何在循环中获取父类别和子类别
How to get parent and child categories in loop
我正在尝试创建一个循环遍历我的所有父类别,回显包含其名称的 <header>
,然后在其下方包含其子类别的列表。如附件图片所示。
至于现在,我得到的只是一个获取类别的简单 foreach
。但我需要帮助才能正确输出它。
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC'
));
foreach($categories as $category) {
//the problem starts here.
}
你可以这样获取列表,更改单选按钮的代码
<?php
$taxonomyName = "category";
$parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'slug', 'hide_empty' => false));
foreach ($parent_terms as $pterm) {
echo '<div class="single_cat col-md-3">';
echo '<h3>'.$pterm->name.'</h3>';
$terms = get_terms($taxonomyName, array('parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false));
foreach ($terms as $term) {
echo "<ul>";
echo '<li><a href="' . get_term_link($term) . '">' . $term->name . '</a></li>';
echo "</ul>";
}
echo '</div>';
}
?>
使用参数 parent
来解决问题。
试试这个方法 -
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC',
'parent' => 0,
));
foreach($categories as $category) {
//Echo parent element
$child_categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC',
'parent' => $category->term_id,
));
// now loop through $child_categories
}
我正在尝试创建一个循环遍历我的所有父类别,回显包含其名称的 <header>
,然后在其下方包含其子类别的列表。如附件图片所示。
至于现在,我得到的只是一个获取类别的简单 foreach
。但我需要帮助才能正确输出它。
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC'
));
foreach($categories as $category) {
//the problem starts here.
}
你可以这样获取列表,更改单选按钮的代码
<?php
$taxonomyName = "category";
$parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'slug', 'hide_empty' => false));
foreach ($parent_terms as $pterm) {
echo '<div class="single_cat col-md-3">';
echo '<h3>'.$pterm->name.'</h3>';
$terms = get_terms($taxonomyName, array('parent' => $pterm->term_id, 'orderby' => 'slug', 'hide_empty' => false));
foreach ($terms as $term) {
echo "<ul>";
echo '<li><a href="' . get_term_link($term) . '">' . $term->name . '</a></li>';
echo "</ul>";
}
echo '</div>';
}
?>
使用参数 parent
来解决问题。
试试这个方法 -
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC',
'parent' => 0,
));
foreach($categories as $category) {
//Echo parent element
$child_categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC',
'parent' => $category->term_id,
));
// now loop through $child_categories
}