Blog / WordPress/ How to Display a Custom Menu in Your WordPress Theme

How to Display a Custom Menu in Your WordPress Theme

Introduction

In a previous article, we explained how to add multiple custom menus in the WordPress admin. This article will show you how to display these newly created custom menus in your front-end theme templates.

How to Call a Custom Menu

Displaying a custom menu is straightforward, primarily using the core WordPress function wp_nav_menu().

Code Example

Here is a basic example. Assume you have registered a menu location named foot-nav:

<?php
wp_nav_menu( array(
    'theme_location' => 'foot-nav', // Must match your registered location
    'container'      => 'nav',      // Outer container HTML tag
    'container_class' => 'foot-nav', // CSS class for the container
    'menu_id'        => '',         // ID for the <ul> element (empty for none)
    'menu_class'     => 'uk-list uk-margin-remove', // CSS class for the <ul>
    'echo'           => true,       // Output HTML directly (false returns a string)
) );
?>

Parameter Explanation

  • theme_location (Required): This must exactly match the location identifier (e.g., 'foot-nav') you registered with register_nav_menus().
  • container: The HTML tag that wraps the menu list. Default is 'div'. Set to false or an empty string to remove the container.
  • container_class: The CSS class name for the outer container.
  • menu_class: The CSS class name for the <ul> element.
  • echo: Controls whether the function outputs HTML directly (true, default) or returns it as a string (false).

Output Result

When the code runs, WordPress retrieves the menu assigned to the 'foot-nav' location from Appearance → Menus and generates the corresponding navigation HTML.

The typical HTML structure generated is:

<nav class="foot-nav">
    <ul id="" class="uk-list uk-margin-remove">
        <li class="menu-item menu-item-type-post_type current-menu-item ...">
            <a href="...">Home</a>
        </li>
        <li class="menu-item ...">
            <a href="...">About Us</a>
        </li>
        ... other menu items
    </ul>
</nav>

FAQ: How to Clean Up Extra CSS Classes?

As shown above, WordPress automatically adds numerous CSS classes to each <li> item (like menu-item-type-post_type) describing its type and state. While useful for styling, this can create bloated HTML.

To simplify these classes, you can use WordPress filters such as nav_menu_css_class and nav_menu_item_id. Detailed instructions for using these filters will be covered in a future article.

Post a Comment

Your email will not be published. Required fields are marked with *.