Adding fields to Menu Items

Last updated Dec 22, 2020

Overview

This guide will demonstrate how to add custom fields to a WordPress Menu Item and how to then modify the Menu Item’s HTML.

Menus are used to organize a group of links (menu items) for your theme to display as navigation. If you are unfamiliar with registering or editing a Menu, please read the WordPress Menu User Guide and Navigation_Menus documentation.

Menu Items are added to a Menu. Learn how to add fields to Menus.

Changelog

  • Added support for Menu in version 5.6.0

Adding fields

The Advanced Custom Fields plugin makes it very easy to add custom fields to a Menu Item, please follow the steps below.

  1. From the Custom Fields admin screen, click the Add New button to create a new field group.
  2. Add the fields you would like to see when editing a Menu Item
  3. Under Locations, select the Menu Item rule and choose ‘All’ (to show this field group on all menu items) or a specific menu/location (to show this field group only for a specific menu’s items)

Change the Instruction placement setting to ‘Below labels’ to best mimic the WP core UI.

Editing fields

Once you have created a field group and assigned it to appear for a Menu Item edit screen, editing the field values is done by navigating to the Appearance > Menus admin page.

WP stores each Menu Item as a post object in the wp_posts table. ACF will store all custom field values in the wp_postmeta table.

Displaying fields

Customizing the HTML for a WordPress Menu Item can be easily done via the wp_nav_menu_objects filter. This filter is run each time a Menu is rendered (via the wp_nav_menu() function) and allows you to modify the Menu Item objects. Each object contains a title value which is output in each menu link <a> element.

This example shows how to modify all Menu Item objects and append an icon if a value exists for the new ‘icon’ field.

functions.php

add_filter('wp_nav_menu_objects', 'my_wp_nav_menu_objects', 10, 2);

function my_wp_nav_menu_objects( $items, $args ) {
    
    // loop
    foreach( $items as &$item ) {
        
        // vars
        $icon = get_field('icon', $item);
        
        
        // append icon
        if( $icon ) {
            
            $item->title .= ' <i class="fa fa-'.$icon.'"></i>';
            
        }
        
    }
    
    
    // return
    return $items;
    
}

Conclusion

Here is a look at how this may look in your browser. Notice the new icon <i> elements!

Notes

Reserved keywords

Please be aware that some reserved keywords exist for Menu Items which may conflict with field names. To avoid any errors that may potentially break the Customizer screen, please avoid using “description” as a field name when attached to a Menu Item.

Save

Related