• Hi folks,

    I’m building a blog using a custom walker for my submenu which looks like this:

    class Submenu_Walker extends Walker_Nav_Menu {
    	function start_el ( &$output, $item, $depth = 0, $args = array(), $id = 0 )
    	{
    		$output .= sprintf('
    			<li>
    				<a href="%s">
    					<span class="title">%s</span>
    					<h2>%s</h2>
    		', get_permalink($item->ID), $item->post_title, $item->post_excerpt);
    	}
    
    	function end_el( &$output, $item, $depth = 0, $args = array() )
    	{
    		$output .= sprintf('
    				</a>
    			</li>
    		');
    	}
    }

    When navigated to the page I would like to add the WordPress active class .current-menu-item to it. I’ve tried adding the default classes from Walker_Nav_Menu like following:

    $class_names = $value = '';
    
    $classes = empty( $item->classes ) ? array() : (array) $item->classes;
    $classes[] = 'menu-item-' . $item->ID;
    
    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
    $class_names = ' class="' . esc_attr( $class_names ) . '"';

    But this didn’t worked as aspected, only the class menu-item-*ID* was added.
    Someone who can help me out with this? Thanks in forward.

Viewing 1 replies (of 1 total)
  • I’ve added the active class to the walker like this:

    1. copied the class Walker_Nav_Menu into functions.php
    2. extended it (just like you did)
    3. added an active class like this changing start_el a bit:

    $activeMenuItemClass = (in_array('current-menu-item', $item->classes)) ? ' class="nav-selected"' : '';
    $output .= $indent . '<li'.$activeMenuItemClass.'>';

    basically, all you need to do is finding out if the key “current-menu-item’ appears in $item->classes and if so you know that this item is the active one and you can attach any class you like to it (or even just simply use the key itself as a class)

Viewing 1 replies (of 1 total)
  • The topic ‘Add active class to custom Walker items’ is closed to new replies.