Skip to content

Instantly share code, notes, and snippets.

@brianhall
Created September 2, 2013 03:32
Show Gist options
  • Save brianhall/6408993 to your computer and use it in GitHub Desktop.
Save brianhall/6408993 to your computer and use it in GitHub Desktop.
With great help from: http://stackoverflow.com/questions/12250866/how-to-add-custom-html-to-wp-nav-menu I needed a way to easily display / add updatable <i> elements inside of nav menu links in Wordpress. I hacked this filter together to help with that. Instructions: 1. Put the first portion of the code into functions.php. 2. Add the item you wi…
<?php
/***
* functions.php, overrides Walker_Nav_Menu from /wp-includes/nav-menu-template.php
***/
class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$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_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $value . $class_names .'>';
$atts = array();
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= '<i class="' . $atts['title'] . '"></i> ';
$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
}
/***
* header.php (or any template file)
***/
wp_nav_menu( array( 'theme_location' => 'primary', 'walker' => new Custom_Walker_Nav_Menu ) );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment