0

I just want to add a class if li is parent class should be level-0 and if li is the child then level-1 etc. I am using the following loop.

 <?php
    $categories = get_categories();
    foreach($categories as $category) {
       echo '<li class="here-i-want-to-add"><a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a></li>';
    }
    ?>

2 Answers 2

1

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>';
    }
}
1
  • get_categories() doesn't return WP_Error (returns empty string on error), but your code made me to reflect on possible usage cases.
    – Max Yudin
    Jan 9, 2022 at 19:29
-1

Greatly inspired by @Sabry's answer.

Term nesting depth is taken into consideration. Also it is one-size-fits-all to work with any taxonomy.

<?php
$taxonomy = 'category'; // your requred

$terms = get_terms(
    array(
        'taxonomy' => $taxonomy,
    )
);

if ( ! is_wp_error( $terms ) ) {
    foreach ( $terms as $term ) {
        $term_ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );

        $term_nesting_depth = count( $term_ancestors );

        $htmlclass = 'level-' . $term_nesting_depth;

        echo '<li class="' . esc_attr( $htmlclass ) . '">';
        echo '<a href="' . esc_url( get_term_link( $term, $taxonomy ) ) . '">';
        echo esc_html( $term->name );
        echo '</a></li>';
    }
}
3
  • I tested this code all parent and child elements got the same class with level-0.
    – stepiadm
    Jan 10, 2022 at 8:50
  • Yes, I've missed some get_ancestors() parameters. It's fixed and tested now.
    – Max Yudin
    Jan 10, 2022 at 11:21
  • I've tried this and it's incorrect.
    – DevSem
    Jan 21, 2022 at 21:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.