category对象存储父ID,如下所示:$category->parent
如果没有父项,则等于0
.
这样,就可以根据的值创建一个等于父类或子父类的变量$category->parent
:
$categories = get_categories();
if ( ! is_wp_error( $categories ) ) {
foreach ( $categories as $category ) {
$htmlclass = ( $category->parent === 0 ) ? "level-0" : "level-1";
echo \'<li class="\' . esc_attr( $htmlclass ).\'">\';
echo \'<a href="\' . esc_url( get_category_link( $category->term_id ) ) . \'">\';
echo esc_html( $category->name );
echo \'</a></li>\';
}
}