You might want to tweak the output of your menu items in WordPress. You can use this to remove or change a link from a specific item.
To do so we can make use of the filter walker_nav_menu_start_el – it’s called for each traversed menu item when building the menu. This is actually done in the nav-menu-template.php script in the class Walker_Nav_Menu and the function start_el.
However this way you can hook into:
1 2 3 4 5 | add_filter( 'walker_nav_menu_start_el', 'disable_specific_link', 10, 4); function disable_specific_link( $item_output, $item, $depth, $args ) { echo "<pre>" . print_r($item, true) . "</pre>"; return $item_output; } |
It will print out each item with attributes and it’s values.
We can make a real world use case and remove the link from a specific item:
1 2 3 4 5 6 7 | add_filter( 'walker_nav_menu_start_el', 'disable_specific_link', 10, 4); function disable_specific_link( $item_output, $item, $depth, $args ) { if( $item->ID == 889) { $item_output = preg_replace('/href="(http:\/\/)?([^"]+)"/', "href=\"#\"", $item_output); } return $item_output; } |
This can be useful when you have several sub pages in your navigation but you don’t have any content in the parent page. The soulution is to make this page not accessible from the navigation.
Hopefully you find this filter as useful as I do. Please leave a comment describing how you use this hook.