Support » Plugins » Hacks » Adding first, last, current classes automatically to get_pages list

  • I have a get_pages setup that I’m using for the main menu of a WordPress site. To make styling easier, I would like to automatically add class=”first” to the first item in the list, class=”last” to the last item in the list, and then class=”active” to the currently active page in the list. These classes can be added to the anchor tag as well, if added them to the li tag isn’t an option.

    I’ve found several resources for making this work use using wp_nav_menu, but only one mention for get_pages ( Which unfortunately only covers one portion of what I’m looking for, and doesn’t work with my setup. I’ve messed around with trying to make it work, but haven’t been successful.

    Here is the code I’m working with, this is before I tried anything on my own relating to this topic.

        $pages = get_pages();
        foreach ( $pages as $pagg ) {
            $menuList = '<li><a href="' . get_page_link( $pagg->ID ) . '" title="' . get_post_meta($pagg->ID, 'Tooltip Text', true) . '">';
            $menuList .= $pagg->post_title;
            $menuList .= '</a></li>';
        echo $menuList;

    I appreciate any help.

Viewing 2 replies - 1 through 2 (of 2 total)
  • I decided to use some jQuery to add the first/last classes to the elements. So really all I need now is a way to add “active” on the current page. There may even be a jQuery solution for that (I will be looking later), but I think doing it through WordPress would be the better option.

    Here’s the jQuery code for adding first/last, just for reference in case anyone stumbles on this thread looking for help.

    <script type="text/javascript">
    	$(window).load(function() {
    	$(' li:first-child').addClass('first');
    	$(window).load(function() {
    	$(' li:last-child').addClass('last');


    Forum Moderator

    untested, I would try something along those lines:

    global $post; $menuList = '<li<?php if( is_page() && $post->ID == $pagg->ID ) echo ' class="active"'; ?>><a href="' . get_page_li.........

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Adding first, last, current classes automatically to get_pages list’ is closed to new replies.