Skip to content

Instantly share code, notes, and snippets.

@levymetal
Last active November 1, 2022 02:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save levymetal/5375456 to your computer and use it in GitHub Desktop.
Save levymetal/5375456 to your computer and use it in GitHub Desktop.
Similar to https://gist.github.com/levymetal/5064699, except this displays all sub-pages as well.
<?php
function my_custom_submenu() {
global $post;
$menu_items = wp_get_nav_menu_items('Menu');
$current_menu_id = 0;
// get current top level menu item id
foreach ( $menu_items as $item ) {
if ( $item->object_id == $post->ID ) {
// if it's a top level page, set the current id as this page. if it's a subpage, set the current id as the parent
$current_menu_id = ( $item->menu_item_parent ) ? $item->menu_item_parent : $item->ID;
break;
}
}
// display the submenu
echo "<ul id='supplementary_menu'>";
foreach ( $menu_items as $item ) {
if ( $item->menu_item_parent == $current_menu_id ) {
$class = ( $item->object_id == $post->ID ) ? "class='current_page_item'" : "";
echo "<li {$class}><a href='{$item->url}'>{$item->title}</a>";
$sub_menu_items = [];
foreach ( $menu_items as $sub_item ) {
if ( $sub_item->menu_item_parent == $item->ID )
$sub_menu_items[] = $sub_item;
}
if ( $sub_menu_items ) {
echo "<ul>";
foreach ( $sub_menu_items as $sub_item ) {
$class = ( $sub_item->object_id == $post->ID ) ? "class='current_page_item'" : "";
echo "<li {$class}><a href='{$sub_item->url}'>{$sub_item->title}</a>";
}
echo "</ul>";
}
echo "</li>";
}
}
echo "</ul>";
}
@jameserie
Copy link

got error on line 26
I have changed it to $sub_menu_items = array(); and it works for me

Thanks

@levymetal
Copy link
Author

Please do not use this script, I have kept it here for archive reasons but a much better script has been developed here: https://gist.github.com/levymetal/5547605

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment