Skip to content

Instantly share code, notes, and snippets.

@antonreshetov
Last active June 22, 2017 22:03
Show Gist options
  • Save antonreshetov/87d5c0fb19a5eecd3c43fe05178640e0 to your computer and use it in GitHub Desktop.
Save antonreshetov/87d5c0fb19a5eecd3c43fe05178640e0 to your computer and use it in GitHub Desktop.
WP custom menu walker
// http://wordpress.stackexchange.com/questions/145984/change-an-li-class-name-in-a-wordpress-custom-menu-walker
<?php
class Main_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl( &$output, $depth = 0, $args = [] ) {
$indent = str_repeat( "\t", $depth );
switch ( $depth ) {
case 0:
$class = 'menu__list-sub';
break;
default:
$class = '';
break;
}
if ( isset( $class ) ) {
$output .= "\n$indent<ul class=\"$class\">\n";
} else {
$output .= "\n$indent<ul>\n";
}
}
function start_el( &$output, $item, $depth = 0, $args = [], $id = 0 ) {
$indent = str_repeat( "\t", $depth );
$attributes = '';
! empty ( $item->attr_title ) and
$item->attr_title !== $item->title and $attributes .= ' title="' . esc_attr( $item->attr_title ) . '"';
! empty ( $item->url ) and $attributes .= ' href="' . esc_attr( $item->url ) . '"';
$current = in_array( "current_page_item", $item->classes ) ? ' current' : '';
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );
$attributes = trim( $attributes );
$title = apply_filters( 'the_title', $item->title, $item->ID );
$item_output = "$args->before<a $attributes class='$current $class_names'>$args->link_before$title</a>" . "$args->link_after$args->after";
switch ( $depth ) {
case 0:
$class = 'menu__item';
break;
default:
break;
}
if ( isset( $class ) ) {
$output .= $indent . '<li class="' . $class . '">';
} else {
$output .= $indent . '<li>';
}
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment