Wordpress: Add active class to $parent_title

2019-09-06 04:52发布

问题:

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>

回答1:

You should use get_pages or wp_get_nav_menu_items. Any WordPress function that returns an array of post objects.

$children = wp_get_nav_menu_items( 'Main Menu' ); // dump to make sure this is an array of objects
echo "<ul id='sub'>";
foreach($children as $item) {
    $class = '';
    if ( $item->object_id == $post->post_parent ){
        $class = 'current_page_ancestor';
    } else if ( $item->object_id == $post->ID ){
        $class = 'current_page_item';
    }
    echo "<li " . $class . "><a href='" . $item->url . "'>" . $item->title . "</a></li>";
}
echo "</ul>";

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



回答2:

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