X

How to Auto Add Subpages to Menus in WordPress

Snippets by IsItWP

Are you looking for a way to display the subpages to menus? While there’s probably a plugin for this, we have created a quick code snippet that you can use to auto add subpages to menus in WordPress.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:


/**
 * Auto add subpages to nav menus
 */
function custom_walker_nav_menu_start_el ( $item_output, $item, $depth, $args) {

	// filter only page menu items
    if( $item->object == 'page' ) {
	
		// set args
		$args = array( 
			'depth' => 1,
			'child_of' => $item->object_id,
			'echo' => 0, 
			'title_li' => '' 
			);
		
		// check for children
		$children = wp_list_pages( $args );

		// append them as list if any
		if ( $children )
			$item_output = $item_output . '<ul class="children" >' . $children . '</ul>';
	
    }
	
	return $item_output;
	
}

add_filter( 'walker_nav_menu_start_el', 'custom_walker_nav_menu_start_el', 10, 4 );

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 11 best WordPress plugins for writers and how to create a guest post submission form in WordPress.

Comments   Leave a Reply

  1. This is still working fine in Sept 2021. However this will impose a problem if those pages are already manually added as well.

    So use this snippet when you want the child pages to show up under it’s parent page menu position. But remove the manually added menu items from Appearance.

    1. Hey Rik, thanks for the advice.

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!