Customizing WordPress Navigation Items using a Walker

Using a fabulous WordPress plugin called External Links to put little arrow icons beside external links was the task this morning.

Installation and setup took less than 60 seconds and all worked well. But wait, there are arrow icons in my header navigation links.

Menu nav links icons

Surely as per the documentation I can add the noicon class to the WordPress header navigation items. Let’s try.

Custom WordPress navigation class

Nope! WordPress adds custom classes to the parent element <li> tag and unfortunately not to the target <a> tags.

Source code of the nav links

So where do I start ‘enhancing’ code to make this work in a future-proof manner? Let’s start with the plugin. I not big on modifying other’s plugins willy-nilly for one-off functionality, but one idea is to make the plugin code look at the parent node and check if it has the noicon class. The way the plugin is designed makes this infeasible in a short amount of time.

I could possibly ‘cheat’ and add some CSS rules like this:

But that’s not me! Let’s be programmatic and hook into a WordPress function. Long story short, looking through the source code of WordPress reveals several filters related to menu items, but none are fine-grained enough to modify the anchor tags individually. However, there is a ray of light. The docs for wp_nav_menu() state that it is possible to pass in a custom Walker_Nav_Menu class. Here is the pertinent code from the base walker class.

Let’s extend the base walker class, add the class noicon to the anchors, and pass that class into wp_nav_menu() like so:

And I’m done!

Expected menu output