Adding first, last, current classes automatically to get_pages list (3 posts)

  1. Preston
    Posted 4 years ago #

    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 (http://wordpress.org/support/topic/adding-current-class-if-using-get_pages?replies=2). 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.

  2. Preston
    Posted 4 years ago #

    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() {
    	$('ul.top-nav li:first-child').addClass('first');
    	$(window).load(function() {
    	$('ul.top-nav li:last-child').addClass('last');
  3. Michael
    Part-Time Forum Moderator
    Posted 4 years ago #

    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.........

Topic Closed

This topic has been closed to new replies.

About this Topic