How to add active class to custom menu using while loop and wp_list_pages

Found the answer here: Add class to the items in wp_list_pages

Just add <?php if(is_page($post->ID )) {?> class="current_page_item" <?php }?>. I added it to the <li> that contained my Overview link in the second level <ul class="children"> as well as the <li> in the top level <ul> if the page doesn’t have children.

<?php echo '<ul>';

$args = array(
    'post_type' => 'page',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'post_parent' => $post->post_parent,
);
$query = new WP_Query($args);
while ($query->have_posts()) {
      $query->the_post();

$child = get_pages('child_of=".$post->ID);

if( count( $child ) != 0 ) : ?>
      <li class="has-children"><span><?php the_title(); ?></span>
      <?php $children = wp_list_pages( "title_li=&child_of=".$post->ID."&echo=0' );
      if ( $children) : ?>
           <ul class="children">
               <li <?php if(is_page($post->ID )) {?> class="current_page_item" <?php }?>><a href="https://wordpress.stackexchange.com/questions/235468/<?php the_permalink(); ?>">Overview</a></li>
               <?php echo $children; ?>
           </ul>
      <?php endif; ?>
      </li>                           
<?php else : ?>
      <li <?php if(is_page($post->ID )) {?> class="current_page_item" <?php }?>><a href="https://wordpress.stackexchange.com/questions/235468/<?php the_permalink(); ?>"><?php the_title(); ?></a>

<?php endif; 
}
echo '</ul>'; ?>

Leave a Comment