Nov
11
2009

Styling wp_list_pages

codeRecently I was approached by someone who wanted to add some styling to the default wordpress navigation. The theme uses <?php wp_list_pages(); ?> for the navigation. The functionality of the site calls for several main pages, with sub pages in each. The layout will be a horizontal menu, with sub pages listed horizontally below.


The Breakdown

Let’s first break down what using <?php wp_list_pages(‘&title_li=’); ?> will spit out in your HTML. This function embeds each page link within a list item of an unordered list. The link for each sub page is then put into a new unordered list witin the initial list item of the parent page. Below is an example of the HTML generated for 1 parent page with 2 child pages.

<ul>
	<li>
      <a href="#">Page 1</a>
<ul>
	<li><a href="#">P1 Sub Page 1</a></li>
	<li><a href="#">P1 Sub Page 2</a></li>
</ul>
</li>
</ul>

For further documentation of this function, see http://codex.wordpress.org/Template_Tags/wp_list_pages.

Putting It To Use

To impliment this into your own theme, you will first want to call the function. I recommend putting this within a <div> with a specified id, to better control the CSS.

HTML:

<div id="main-nav"></div>

Then style the <ul> and <li> elements by nexting them within #main-nav.

CSS:

#main-nav{
   overflow: hidden;
}
#main-nav ul{
   list-style-type: none;
}
#main-nav li{
   float:left;
}
#main-nav li a{
   color:#4aa1ff;
   text-decoration:none;
}
#main-nav li a:hover{
   color:#333333;
}

At this point, every page and subpage will have the same styles. Let’s take this a step further by adding some CSS for those sub pages.

#main-nav li li a{
   color:#fb7200;
}
#main-nav li li a:hover{
   color:#333333;
}

If we created children in our sub pages, we could simply apply the same logic in our CSS and add another section #main-nav li li li a{} with different styles from the initial 2.

Categories
Tutorial
Comments
1 Comment
Author
Bob Pease