0

I have next category dropdown filter that atm supports only two levels "parent -> Child" and I want to get the third "parent -> child -> child".

I have two functions:

function reviews_display_categories_filter( $ancestors = array(), $permalink = '', $parent = 0 ){
    global $reviews_slugs;
    $categories = get_terms( 'review-category', array(
        'hide_empty' => false,
        'parent' => $parent
    ));

    if( !empty( $categories ) ){
        foreach( $categories as $category ){
            $option = '<option value="'.esc_attr( $category->slug ).'" '.( isset( $_GET[$reviews_slugs['review-category']] ) && $_GET[$reviews_slugs['review-category']] == $category->slug ? 'selected="selected"' : '' ).'>';
            $option .= $category->name.' ('.reviews_count_filter( $category ).')';
            $option .= '</option>';
            echo  $option;

            if( in_array( $category->term_id, $ancestors ) ){
                $children = get_term_children( $category->term_id, 'review-category' );
                reviews_display_category_children( $children, $ancestors, $permalink );
            }
        }
    }
}

function reviews_display_category_children( $children, $ancestors, $permalink, $depth = 2 ){
    global $reviews_slugs;
    if( !empty( $children ) ){
        foreach( $children as $child ){
            $term = get_term_by( 'id', $child, 'review-category' );

            $option = '<option value="'.esc_attr( $term->slug ).'" '.( isset( $_GET[$reviews_slugs['review-category']] ) && $_GET[$reviews_slugs['review-category']] == $term->slug ? 'selected="selected"' : '' ).'>';
            $option .= str_repeat('&nbsp;&nbsp;', $depth).$term->name.' ('.reviews_count_filter( $term ).')';
            $option .= '</option>';
            echo  $option;

            if( in_array( $child, $ancestors ) ){
                $children = get_term_children( $child, 'review-category' );
                reviews_display_category_children( $children, $ancestors, $permalink );
            }
        }
    }
}

And it outputs next list: Output

I want output like this:

Parent
-Child 1
--Child 2

I tried several things, but nothing works at the moment.

1

Just from skimming your code, it actually pretty much does the same as the WordPress API function wp_dropdown_categories(). It isn't as sophisticated though, no insult intended. Because wp_dropdown_categories() is capable of displaying deeper leveled hierarchies - correctly - then your own function, I can't see a reason for not just using wp_dropdown_categories() for your purpose. If there is a reason, that I have overlooked or just can't see, then you should take a look at the source of wp_dropdown_categories() to get some inspiration and/or guidance from it.

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.