Performance: Navigation walker classes
This affects page load speed and rendering by controlling how navigation menus are built and output in HTML.
<?php class Efficient_Walker extends Walker_Nav_Menu { function start_el(&$output, $item, $depth=0, $args=null, $id=0) { $classes = implode(' ', $item->classes); $output .= "<li class='$classes' role='menuitem'><a href='" . esc_url($item->url) . "'>" . esc_html($item->title) . "</a></li>"; } } wp_nav_menu(array('walker' => new Efficient_Walker())); ?>
<?php class Slow_Walker extends Walker_Nav_Menu { function start_el(&$output, $item, $depth=0, $args=null, $id=0) { $output .= "<li><div class='extra-wrapper'><a href='" . esc_url($item->url) . "'>" . esc_html($item->title) . "</a></div></li>"; } } wp_nav_menu(array('walker' => new Slow_Walker())); ?>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Minimal semantic walker | Low DOM nodes | Single reflow | Low paint cost | [OK] Good |
| Non-semantic, deep nested walker | High DOM nodes | Multiple reflows | High paint cost | [X] Bad |
start_el controls the start of each menu item element.end_el ends a menu item, start_lvl and end_lvl handle submenu levels.class My_Walker extends Walker_Nav_Menu {
function start_el(&$output, $item, $depth=0, $args=null, $id=0) {
$output .= "" . $item->title . "";
}
}
wp_nav_menu(array('walker' => new My_Walker()));class Custom_Walker extends Walker_Nav_Menu {
function start_el($output, $item, $depth=0, $args=null, $id=0) {
$output .= "start_el must accept &$output by reference to modify it properly.$output without & reference, so changes won't affect the original output string.Pass the test and this pattern moves unknown