Reputation: 43
<?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);?>
<li><a href="<?php echo get_permalink($post->post_parent) ?>"><?php echo $parent_title;?></a></li>
<?php echo $children; ?>
<?php } ?>
The code above lists the parent and all child pages in a list.
Parent Page
Child Page
Child Page class="active"
Child Page
Child Page
I would like to add a class of "active" to the currently active page. Any help is greatly appreciated. Thanks
Upvotes: 2
Views: 19740
Reputation: 339
You can easily add active and other classes by checking the $post->post_title
against the $item->title
function addLinkClassesWithActive( $atts, $item, $args ) {
global $post;
// check if the item is in the primary menu
if( $args->theme_location == 'main-nav' ) {
// add the desired attributes:
$atts['class'] = $post->post_title === $item->title ? 'mdl-layout__tab is-active' : 'mdl-layout__tab';
}
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'addLinkClassesWithActive', 10, 3 );
I am using this myself and stripping out the wrapping container, the ul, and the li tags so that I have just a link. See example below.
<nav role="navigation" class="mdl-navigation mdl-layout--large-screen-only" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div class="mdl-tabs mdl-js-tabs mdl-js-ripple-effect">
<?php
$primaryMenu = array(
'container' => false,
'theme_location' => 'main-nav',
'items_wrap' => '%3$s',
'echo' => false,
);
echo strip_tags( wp_nav_menu( $primaryMenu ), '<a>' );
?>
</div>
</nav>
Upvotes: 1
Reputation: 1677
To look for a specific page and add an active class to it, you can try using is_page and define the URL/slug of the page.
<a class="<?php if (is_page('name-of-page')) echo 'active'; ?>" href="#">Link</a>
Upvotes: 14