• I am using the following code to get the subcategories of a specific category and its posts as a side navigation.
    Its creates navigation structure like following:

    • Ancestor category
    • parent category
    • post1
    • post2
    • post3

    When i am in post3 i want to make the Ancestor category also active state.

    Its taking me forever to find out how to make the ancestor category active when the post is being viewed. Any help will be much appreciated.

    <?php
    
    					foreach( get_categories('hide_empty=0&include=4') as $cat ) :
    							if( !$cat->parent ) {
                        echo '<ul id="nav-side">';
                        process_cat_tree( $cat->term_id );
                                }
                        endforeach;
    
                        wp_reset_query(); //to reset all trouble done to the original query//
    
                        function process_cat_tree( $cat) {
                        $args = array('category__in' => array( $cat ), 'numberposts' => -1);
                        $cat_posts = get_posts( $args );
    
    						global $post;
    						if( $cat_posts ) :
    						foreach( $cat_posts as $menuPost ) :
    						echo '<li class="child';
    						if ( $menuPost->ID == $post->ID ) { echo ' current'; }
    						echo '">';
    						echo '<a href="' . get_permalink( $menuPost->ID ) . '">' . $menuPost->post_title . '</a>';
    						echo '</li>';
    						endforeach;
    						endif;
    
                        $next = get_categories('hide_empty=0&orderby=id&order=DESC&parent=' . $cat);
    
    					$post_cats = array(); foreach(get_the_category($post->ID) as $post_cat)  $post_cats[] = $post_cat->term_id;
    
                        if( $next ) :
                        foreach( $next as $cat ) :
                        echo '<li' . (in_array($cat->term_id,$post_cats)?' class="active"':'') . '>         
    
    					<a href="#">' . $cat->name . '</a>
    
    					<ul class="sub-menu">';
    					process_cat_tree( $cat->term_id );
                        endforeach;
                        endif;
                        echo '</ul>
    					</li>';
                        }
                        ?>
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)

The topic ‘active ancestor category while on the post’ is closed to new replies.