I’m using WordPress’s wp_list_pages to display a nav of pages on the site.
Some pages have children so I need a dropdown menu below those links.
The html is something like this
<ul class="">
<li class="page_item page-item-6 current_page_item"><a href="/">Home</a></li>
<li class="page_item page-item-6 current_page_item"><a href="/">Profile</a></li>
<li class="page_item page-item-8 page_item_has_children dropdown">
<a href="">Products & Services</a>
<ul class='children'>
<li class="page_item page-item-17"><a href="">Buying</a></li>
<li class="page_item page-item-19"><a href="">Selling</a></li>
<li class="page_item page-item-23"><a href="">Managing</a></li>
</ul>
</li>
</ul>
I wanted to use bootstrap to create the nav and dropdown menus.
Something like – http://www.ttmt.org.uk/nav/
The html for this is something like this.
<ul class="nav navbar-nav">
<li><a href="#">Home</a></li>
<li><a href="#">Profile</a></li>
<li class="dropdown">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">Messages <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Inbox</a></li>
<li><a href="#">Drafts</a></li>
<li><a href="#">Sent Items</a></li>
</ul>
</li>
</ul>
I need to add a ‘dropdown’ class the li and ul containing the child pages. I also need to add a class and a data-toggle attribute to the ‘a’ tag.
How can I add these clases when I using wp_list_pages and the nav is created dynamically.
I’m using this function to add ‘dropdown’ to li containin the child pages
function add_parent_class( $css_class, $page, $depth, $args ){
if ( ! empty( $args['has_children'] ) )
$css_class[] = 'dropdown';
return $css_class;
}
add_filter( 'page_css_class', 'add_parent_class', 10, 4 );
How could I extened this function add the other classes I need
To achieve this functionality, we can not use filters only. We will have to extend the Walker class of WordPress.
I am assuming that you have called wp_list_pages like this:
We will pass value to walker paramter. That paramter would be object of a class that we will create now. Add this class in functions.php of your theme or in site specific plugin
Above class adds all the classes you wanted.
Now, we need to pass the object of this class to wp_list_pages. So it would look something like this
I Hope it helps! You don’t need to write code on filter
page_css_class
anymore. 🙂