按层次显示类别和子类别自定义帖子

met*_*box 0 wordpress custom-post-type

我使用此代码来获取所有类别和子类别,这项工作但不按层次结构显示子类别。

\n\n
$args = array(\n                \'hide_empty\'    => 1,\n                \'hierarchical\'  => 1,\n                \'pad_counts\'    => false\n            );\n\n$categories = get_terms(\'project_category\', $args); \necho \'<ul>\';\n            foreach ($categories as $category) {\n                echo \'<li class="s"></li><li><a href="#\'. $category->slug .\'" data-filter=".category-\'. $category->slug .\'">\'. $category->name .\'</a> B</li>\';\n            }\necho \'</ul>\';\n
Run Code Online (Sandbox Code Playgroud)\n\n

我无法使用 wp_list_categories() 因为 don\xc2\xb4t 显示 ul 标签并添加一些其他 div

\n\n

因为我可以区分未使用的类别和子类别 wp_list_categories()

\n

Sam*_*ikh 5

使用这种方式显示类别和子类别

<?php

$parent_cat_arg = array('hide_empty' => false, 'parent' => 0 );
$parent_cat = get_terms('category',$parent_cat_arg);//category name

foreach ($parent_cat as $catVal) {

    echo '<h2>'.$catVal->name.'</h2>'; //Parent Category

    $child_arg = array( 'hide_empty' => false, 'parent' => $catVal->term_id );
    $child_cat = get_terms( 'category', $child_arg );

    echo '<ul>';
        foreach( $child_cat as $child_term ) {
            echo '<li>'.$child_term->name . '</li>'; //Child Category
        }
    echo '</ul>';

}
?>
Run Code Online (Sandbox Code Playgroud)

输出 在此输入图像描述