The category object stores the parent ID like this: $category->parent
In the event that there is no parent it’s equal to 0
.
In this way, it is possible to create a variable equal to the parent class or the child parent according to the value of $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>';
}
}