Building a Cleaner Navigation in WordPress

Building a Cleaner Navigation in WordPress

I’ve decided to start publishing my web development articles and tutorials exclusively on the Wanderoak blog, which you may know, is my company. Head on over there to read more articles you’ll enjoy, if you like this one.

This is something I’ve played around with for a couple years. I dislike the default output of the WordPress navigation walker, however, it has some useful qualities. Specifically, the classes on links, I use them quite a lot to style different states.

A lot of websites have a flat one-level navigation, which means, ideally the nav can and should look like this:

There is no default way in WordPress to output this. At best, you can have

The only reason the <li> element is useful is because it contains the classes. That’s it. However, the navigation would function just as well if the classes were on the <a> tag. I used to have this little piece of code that I would insert directly into the navigation area in my WordPress files, until a few days ago when I realized how absurd it was.

Why was I copying and pasting this chunk of code constantly? Why had I not already made a function for this? So that’s exactly what I did. It only took me about 10 seconds. I made a simple function that you pass the theme-location to when you call it, and it spits out the correct menu, formatted in a nice and clean way with the classes intact on the <a> tag.

Using String Replacement to Clean up the Menu Output

I’m doing three things:

  1. I’m calling the default navigation walker with the options: theme location, no container, item wrap with the classes, and I don’t want it to echo since I’m going to store it first, do some extra things and then output it.
  2. I’m getting rid of the <a> tag, and replacing the li part of the list item tag with a, so it becomes an anchor tag with the classes that were originally on the <li>.
  3. Then I output the cleaned up menu.

I’ve googled other solutions to this issue and the best answer people seem to come up with is ‘build a custom Walker class’ and that’s awesome and everything, but why would I do that when I do this? Obviously, what I’m doing is a hack, but it’s a simple hack, and I prefer it to coding a custom Walker.

So here’s the function I wrote: (If you can’t see the gist, here’s the link.)

I’m currently considering and experimenting with ways to accomplish the same level of cleanliness for menus with more than one level, but I’ve yet to figure out a way I’m completely happy with. What do you think? Tweet me your comments and thoughts!

P.S. A lot of this code is adapted from Zoe Rooney.

P.P.S. If you liked this, maybe you’ll my tutorial on how to deploy WordPress themes with Git too!