Skip to content

Instantly share code, notes, and snippets.

@Miri92
Last active April 10, 2024 17:03
Show Gist options
  • Save Miri92/ffb67e6be29029e745078a914786238d to your computer and use it in GitHub Desktop.
Save Miri92/ffb67e6be29029e745078a914786238d to your computer and use it in GitHub Desktop.
Wordpress walker class for wp_nav_menu() - change item and submenu class also add caret icon inside has-childiren item.
<?php
class My_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl(&$output, $depth = 0, $args = array()) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"dropdown-menu\">\n";
}
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0)
{
global $wp_query;
$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 ) );
// Check our custom has_children property.here is the points
if(in_array('menu-item-has-children', $classes ) && $depth == 0) {
// Your Code
$class_names = ' class="dropdown custom-drop ' . esc_attr( $class_names ) . '"';
} else {
$class_names = ' class="' . esc_attr( $class_names ) . '"';
}
$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
$id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $value . $class_names .'>';
$attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
$attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
$attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
$attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
$item_output = $args->before;
// Check our custom has_children property.here is the points
if(in_array('menu-item-has-children', $classes ) && $depth == 0) {
$item_output .= '<i class="caret hidden-xs"></i>';
}
$item_output .= '<a'. $attributes .'>';
$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 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment