Build a Custom Menu from Parent Menu Items with Children

Posted on Dec 15, 2025

by Jimmy


Fetches a WordPress menu, filters for top-level items that contain children, and renders them as a structured menu. Useful for footer menus.

PHP
        
            <div class="footer__menu">
		<?php 
		/** 
		* Grab all menu items that have children 
		* and create a custom footer menu 
		*/
	
		$menu_name = 'main-menu';
		$menu_items = wp_get_nav_menu_items($menu_name);
		
		if ($menu_items) :
			// Group menu items by parent
			$menu_tree = array();
			foreach ($menu_items as $item) {
				if ($item->menu_item_parent == 0) {
					$menu_tree[$item->ID] = array(
						'item' => $item,
						'children' => array()
					);
				} else {
					if (isset($menu_tree[$item->menu_item_parent])) {
						$menu_tree[$item->menu_item_parent]['children'][] = $item;
					}
				}
			}
			
			// Filter to only show parents that have children
			$parents_with_children = array_filter($menu_tree, function($item) {
				return !empty($item['children']);
			});
			
			if (!empty($parents_with_children)) : ?>

				<div class="footer__menu-columns">

					<?php foreach ($parents_with_children as $parent_item) : ?>

						<div class="footer__menu-column">

							<h3 class="footer__column-title">
								<?= esc_html(tm_get_menu_item_footer_label($parent_item['item'])); ?>
							</h3>
							
							<div class="footer__links-container">

								<ul class="footer__links">

									<?php foreach ($parent_item['children'] as $child_item) : ?>

										<li class="footer__link">
											<a href="<?= esc_url($child_item->url); ?>" 
											   target="<?= $child_item->target ? '_blank' : '_self'; ?>">
												<?= esc_html(tm_get_menu_item_footer_label($child_item)); ?>
											</a>
										</li>

									<?php endforeach; ?>

								</ul>

							</div> <!-- END footer__links-container -->

						</div> <!-- END footer__menu-column -->

					<?php endforeach; ?>

				</div> <!-- END footer__menu-columns -->

			<?php endif;

		endif; ?>

	</div> <!-- END footer__menu -->        
    

Back to Snippets