DigitalGenius

Custom menu shortcode

Rendering a WordPress menu from a shortcode is a small problem that is easy to solve badly. Here is the approach that holds up.

The requirement

You want to place a registered menu inside post or block content, often inside a column or a callout, without hard-coding a menu ID into a template. The shortcode has to accept a menu name or location, degrade sensibly when the menu does not exist, and not output markup that breaks the surrounding layout.

The implementation

Register the shortcode, validate the requested menu against the menus that actually exist, and hand off rendering to the core menu walker rather than building markup by hand. Core handles the current-page classes, the nesting and the accessibility attributes that users and search engines both rely on.

What the shortcode should do

Common mistakes

Hard-coding a term ID, echoing unescaped attributes, and forgetting that the shortcode will run inside contexts where the menu walker's default container breaks the parent grid. Each of those turns a five-minute task into a support ticket.

On modern WordPress, a block or a reusable pattern is usually the better answer. Keep the shortcode for legacy content and for places where only a shortcode can reach.

Talk to us about your project

If you are planning a WordPress build, a WooCommerce migration or a growth programme, we will tell you honestly whether it is a fit.

Get in touch