
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