Adding More Classes to wp_list_pages()


If you’re trying to style nested items in wp_list_pages() the task can be daunting. You’ll apply a style to an <li> then have to unapply those styles for the nested <li>s, and if you’re dropdowns get any deeper, you CSS can become overwhelming. It’s a little better if you don’t care about IE, because then you can use those fancy CSS selectors like ul > li, or ul li > li to target certain depths. But if you’re stuck fighting with IE, maybe this will help.

Just stick this in your functions.php file (plugin coming soon) and you’ll end up with a few extra class to help you out. (See sample output at the end.)

You can now download the plugin version from this page. I’ve made some improvements to the code as well as added support for wp_list_categories() and wp_nav_menu()

These classes are added in addition to what WordPress supplies. Classes are added according to depth, rather than parent-child relationships.

  • ul.level-1-ul
  • li.level-1-li
    • a.level-1-a
    • a.level-1-a
  • li.level-1-li
    • ul.level-2-ul
      • li.level-2-li
        • a.level-2-a
    • a.level-1-a

6 thoughts on “Adding More Classes to wp_list_pages()”

  1. Hey that’s a pretty good mod. Doesn’t WP_list_pages give children UL’s a class of children like wp_list_categories does? It almost seems easier to roll your own wp_list_pages by using get_pages( $args ) and running a foreach over it.

    1. Each child <ul> gets a class of ‘children’ but there’s nothing to separate children from grandchildren.

      I could do things like .children li {} and .children .children li { } but I hate having to ‘undo’ styles that I don’t want on my grandchildren…

      I realize the ‘C’ in ‘CSS’ is for cascading, but sometimes I don’t want all my styles to cascade!

      There’s probably an easier way (almost always is when I do something) but for now this one is working for me.

    1. I hope it works for you – please let me know if you encounter any problems.

      Also, I’ve just updated this to 1.1 which fixes a minor issue regarding preserving IDs. (a very simple fix on line 72 if you want to make the update manually)

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: