How to render WordPress menu items without a custom Walker

In recent work where I’ve been using tailwindcss to build my UI, I’ve come up against the challenge of dealing with WordPress’ default menu markup. One possible solution here could be to write a custom walker class but, for something quick and simple, the following code snippet got me where I needed to be with less headache.

<?php $menu_location = 'some_menu_location'; ?>
<?php if ( has_nav_menu( $menu_location ) ): ?>
<?php $menu_items = wp_get_nav_menu_items( wp_get_nav_menu_name( $menu_location ) ); ?>
<?php foreach ( $menu_items as $menu_item ): ?>
<a href="<?= esc_url( $menu_item->url ) ?>"
target="<?= esc_attr( $menu_item->target ?: '_self' ) ?>"
class="<?= esc_attr( implode( ' ', $menu_item->classes ) ) ?>"><?= esc_html( $menu_item->title ) ?></a>
<?php endforeach; ?>
<?php endif; ?>

This approach is also great for printing a WordPress menu as nothing but <a> tags which is really useful when dealing with things like footer links. It makes it quick and easy to print the simplest of markup whilst still leveraging WordPress’ menu system to control the menu from the admin.

Got a project? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.