首页 > 解决方案 > 如何在循环中获取父子类别

问题描述

我正在尝试创建一个循环,该循环遍历我的所有父类别,回显<header>包含其名称的 a ,然后在其下方回显包含其子类别的列表。如附图所示。

至于现在我得到的只是一个简单foreach的类别。但我需要帮助才能正确输出。

$categories = get_categories( array(
    'orderby' => 'name',
    'order'   => 'ASC'
));

foreach($categories as $category) {
    //the problem starts here.
} 

在此处输入图像描述

标签: phpwordpresscategories

解决方案


您可以像这样获取列表,更改单选按钮的代码

<?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>'; 
                }


                 ?>

推荐阅读