I am displaying a sidebar menu listing Parent and child pages.
- Parent
- Child page one
- Child page two
- Child page three
My code is applying the class .current_page_item to the active child pages, but not to the active parent page. I would like the parent to have the class .current_page_item too when on that page.
<?php
if($post->post_parent)
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
else
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
if ($children) {
$parent_title = get_the_title($post->post_parent);?>
<ul id="sub">
<li><a href="<?php echo get_permalink($post->post_parent) ?>"><?php echo $parent_title;?></a></li>
<?php echo $children; ?>
</ul>
<?php } ?>
Here is an idea of what is being outputted:
<ul id="sub">
<li><a href="#">Parent</a></li>
<li class="page_item page-item-19 current_page_item"><a href="#">Child page</a></li>
<li class="page_item page-item-21"><a href="#">Child page</a></li>
<li class="page_item page-item-23"><a href="#">Child page</a></li>
</ul>
You should use get_pages or wp_get_nav_menu_items. Any WordPress function that returns an array of post objects.
This gets an array of WordPress posts, then loops through them.
If the post ID in the current iteration is the same as the parent of the post you are viewing, add the class 'current_page_ancestor.'
If the post ID in the current iteration is the same as the post you are viewing, add the class 'current_page_item.'
Thanks for all the help pmandell.
I found the answer to my question here: http://codex.wordpress.org/Function_Reference/wp_list_pages#List_topmost_ancestor_and_its_immediate_children