Skip to content

Instantly share code, notes, and snippets.

@efrigoli
Created January 9, 2025 20:06
Show Gist options
  • Save efrigoli/c13d7f4aa3d40653436c45e3256c96d5 to your computer and use it in GitHub Desktop.
Save efrigoli/c13d7f4aa3d40653436c45e3256c96d5 to your computer and use it in GitHub Desktop.
This code provides an example of a custom nav walker class to extend the WordPress Core Walker_Nav_Menu class. The custom nav walker modifies the menu output to use buttons instead of links for menu items with submenus.
<?php
/*
* All code is intended as a learning example only and will require modification to function properly based on the project needs.
*/
/**
* This class extends the WordPress Core Nav Walker class to create list output
* with buttons instead of links for items with submenus.
*
* @see https://developer.wordpress.org/reference/classes/walker_nav_menu/
*/
class Custom_Nav_Walker extends Walker_Nav_Menu {
/**
* Starts the element output for the menu.
*
* @param string $output Used to append additional content (passed by reference).
* @param object $item Menu item data object.
* @param int $depth Depth of menu item.
* @param object $args An array of wp_nav_menu() arguments.
* @param int $id ID of the current menu item. Default 0.
* @see https://developer.wordpress.org/reference/classes/walker_nav_menu/start_el/
*/
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
// Wrap each menu item in a list item element with classes and depth level provided from the $item object.
$output .= "<li class='" . implode( ' ', $item->classes ) . ' menu-item-level-' . $depth . "'>";
// If the menu item does not have a submenu, output as an anchor element.
if ( ! ( in_array( 'menu-item-has-children', $item->classes, true ) ) ) {
// If the menu item is the current page, add the aria-current attribute.
if ( ( in_array( 'current-menu-item', $item->classes, true ) ) ) {
$output .= '<a href="' . $item->url . '" aria-current="page">';
} else {
// If the menu item is not the current page, output as an anchor element with a URL provided from the $item object.
$output .= '<a href="' . $item->url . '">';
}
// Output the menu item title and close the anchor element.
$output .= $item->title;
$output .= '</a>';
} else {
/** If the menu item does have a submenu, output the item as a button element
* with an aria-haspopup attribute of true and an aria-expanded attribute of false.
*/
$output .= '<button class="megamenu-button" aria-haspopup="true" aria-expanded="false">';
// Output the menu item title and close the button element.
$output .= $item->title;
$output .= '</button>';
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment