Skip to content

Adding custom field data into WordPress menus

One of the problems almost everyone has with developing CMS driven websites is generating navigation menus; particularly pretty or heavily customised menus that can be easily updated by the end user.

WordPress (like Drupal) has a really excellent menu builder tool that you can use to easily create hierachical menus that you assign to “slots” in your theme. But what happens if you need to modify the standard html output of the menu? For example to pull in some information about the menu item’s target, such as custom field data about the Page or Post.¬†You make a custom Walker…

Subclass Walker_Nav_Menu, include it in your theme’s functions.php file, and duplicate the start_el() method. If you look at the properties of the $item Object passed into the method, you’ll find that $item->object_id is particularly useful, as it refers to the WordPress Post/Page/CPT that this menu item is linked to. Now you’re in business and can just query for any post_meta information you want to inject into the menu html.

In the example below I added the css-id custom field data from the “target” to the list item’s id property. This means I can more reliably add bespoke background images and css styles to my uber-cool menus without having to worry about people deleting the initial menu entry I created. Which is nice for me, great for my customers, and even better for their customers…

function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 )


$id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args );

//Add any custom ID added to the object...
 $css_id = ( get_post_meta($item->object_id, 'css-id', true) ) ? get_post_meta($item->object_id, 'css-id', true) : null;
 $id = ( $css_id ) ? $id . " " . $css_id : $id ;

$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

Need a freelance web developer near Bath to turn your web designs into reality? We build websites for small businesses, design agencies and freelance designers, quickly, efficiently and cost-effectively. Don’t hesitate to give us a bell on 01380 830224. We’re sure we can help!

This entry was posted in Wordpress. Bookmark the permalink.


Sorry, comments are closed on this page.